commit 84f0e312ec4dd3e6dda4e585c236faf57b781473
parent 394c28d72e0ab490cbef294566c95e5500f335df
Author: anon <anon@example.com>
Date: Wed, 11 Nov 2026 02:31:12 +0000
Resume browser audio on touch release
Diffstat:
4 files changed, 82 insertions(+), 6 deletions(-)
diff --git a/client/browser/index.html b/client/browser/index.html
@@ -557,8 +557,8 @@ show();
canvas.transferControlToOffscreen = undefined;
}
Module.audioContext = new AudioContext();
- // Load immediately; browsers unlock audio on the first game interaction.
- for (const type of ['pointerdown', 'keydown']) {
+ // Touch activation arrives on release; retry after a premature pointerdown resume.
+ for (const type of ['pointerdown', 'pointerup', 'touchend', 'keydown']) {
document.addEventListener(type, resumeAudio, true);
}
status.textContent = 'Starting Anarchy Online...';
diff --git a/client/runtime/browser_profile.js b/client/runtime/browser_profile.js
@@ -113,6 +113,15 @@ addToLibrary({
worker.postMessage({init: {session, detailed, memory: wasmMemory.buffer,
currentFunction, phase, thread, started: performance.timeOrigin + performance.now(), visibility: document.visibilityState,
client: {userAgent: navigator.userAgent, width: Module.canvas.width, height: Module.canvas.height}}});
+ if (Module.audioContext) {
+ const recordAudioState = () => worker.postMessage({
+ events: [{name: 'audio context state', ph: 'i', s: 't', pid: 1, tid: 0,
+ ts: (performance.timeOrigin + performance.now()) * 1000,
+ args: {state: Module.audioContext.state}}], frames: [], metrics: {}, dropped: 0
+ });
+ Module.audioContext.addEventListener('statechange', recordAudioState);
+ recordAudioState();
+ }
worker.onmessage = event => {
if (event.data.free) _free(event.data.free);
else console.log(event.data);
diff --git a/client/tests/browser_profile.mjs b/client/tests/browser_profile.mjs
@@ -128,6 +128,7 @@ for (const search of ['', '?profile=0', '?profile=other']) {
{
let library;
const workers = [], messages = [], channels = [];
+ const audioContext = Object.assign(new EventTarget(), {state: 'suspended'});
const context = vm.createContext({
addToLibrary: value => { library = value; }, URLSearchParams, URL,
location: {search: '?profile=1'}, crypto: {randomUUID: () => 'test'},
@@ -135,17 +136,23 @@ for (const search of ['', '?profile=0', '?profile=other']) {
BroadcastChannel: class { constructor() { channels.push(this); } },
wasmMemory: {buffer: new SharedArrayBuffer(64)},
document: {baseURI: 'https://example.test/', visibilityState: 'visible', addEventListener() {}},
- navigator: {userAgent: 'test'}, Module: {canvas: {width: 640, height: 480}},
+ navigator: {userAgent: 'test'}, Module: {canvas: {width: 640, height: 480}, audioContext},
performance: {timeOrigin: 1000, now: () => 10}, stringToNewUTF8: value => value
});
vm.runInContext(fs.readFileSync(new URL('../runtime/browser_profile.js', import.meta.url), 'utf8'), context);
assert.equal(library.ao_profile_start(4, 8, 7), '1:test:8:7');
assert.deepEqual(workers, ['/wasm/profile-worker.js']);
- assert.equal(messages.length, 1);
+ assert.equal(messages.length, 2);
assert.equal(messages[0].init.detailed, true);
+ assert.equal(messages[1].events[0].name, 'audio context state');
+ assert.equal(messages[1].events[0].args.state, 'suspended');
+ assert.equal(messages[1].events[0].ts, 1010000);
channels[0].onmessage({data: {register: {sample: 32, entry: 0x1234, thread: 8}}});
- assert.equal(messages[1].register.sample, 32);
- assert.equal(messages[1].memory, context.wasmMemory.buffer);
+ assert.equal(messages[2].register.sample, 32);
+ assert.equal(messages[2].memory, context.wasmMemory.buffer);
+ audioContext.state = 'running';
+ audioContext.dispatchEvent(new Event('statechange'));
+ assert.equal(messages[3].events[0].args.state, 'running');
}
console.log('PASS: profiling stays off until explicitly enabled');
diff --git a/tests/e2e/audio.test.mjs b/tests/e2e/audio.test.mjs
@@ -0,0 +1,60 @@
+import assert from 'node:assert/strict';
+import {before, test} from 'node:test';
+import {buildServer, withFixture} from './fixture.mjs';
+import {GameTest} from '../../tools/client/game_test.mjs';
+
+before(buildServer);
+
+test('first touch release unlocks audio after an early resume rejection', {timeout: 120_000}, async () => {
+ await withFixture('audio-touch', async fixture => {
+ const context = await fixture.browser.newContext({viewport: {width: 390, height: 844},
+ isMobile: true, hasTouch: true,
+ userAgent: 'Mozilla/5.0 (Android 17; Mobile; rv:159.0) Gecko/159.0 Firefox/159.0'});
+ assert.equal((await context.request.post(fixture.url + '/browser-launch')).status(), 200);
+ const batches = [];
+ await context.route('**/admin/browser-profile/*', async route => {
+ batches.push(route.request().postDataJSON());
+ await route.fulfill({status: 204});
+ });
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ fixture.games.push(game);
+ const input = await context.newCDPSession(page);
+ const read = async expression => (await input.send('Runtime.evaluate', {expression, returnByValue: true})).result.value;
+
+ // Require an already-activated gesture instead of queuing a premature resume.
+ await page.addInitScript(() => {
+ window.audioResumes = [];
+ const resume = AudioContext.prototype.resume;
+ AudioContext.prototype.resume = function() {
+ const active = navigator.userActivation.isActive;
+ window.audioResumes.push({type: window.event?.type, active});
+ if (!active) return Promise.reject(new DOMException('Touch has not ended', 'NotAllowedError'));
+ return resume.call(this);
+ };
+ });
+ await page.goto(fixture.url + '?profile=1');
+ await game.waitFor('audio context initialized', () => read("typeof Module !== 'undefined' && !!Module.audioContext"));
+ await game.waitFor('first game frame', () => read("typeof gameReady !== 'undefined' && gameReady"));
+ assert.equal(await read('Module.audioContext.state'), 'suspended');
+ assert.equal(await read('navigator.userActivation.hasBeenActive'), false);
+
+ // CDP reads do not grant activation; only these real browser touch events do.
+ await input.send('Input.dispatchTouchEvent', {type: 'touchStart', touchPoints: [{x: 195, y: 200}]});
+ assert.equal(await read('Module.audioContext.state'), 'suspended');
+ assert.equal(await read('audioResumes.some(attempt => !attempt.active)'), true);
+ await input.send('Input.dispatchTouchEvent', {type: 'touchEnd', touchPoints: []});
+ await game.waitFor('audio running after finger release', () => read("Module.audioContext.state === 'running'"));
+ assert.equal(await read('audioResumes.some(attempt => attempt.active)'), true);
+ const clock = await read('Module.audioContext.currentTime');
+ await game.waitFor('audio clock advancing', async () => await read('Module.audioContext.currentTime') > clock);
+ await game.ready();
+ await game.waitFor('audio state profile uploaded', () => batches.some(batch =>
+ batch.traceEvents.some(event => event.name === 'audio context state' && event.args.state === 'running')));
+ const states = batches.flatMap(batch => batch.traceEvents)
+ .filter(event => event.name === 'audio context state').map(event => event.args.state);
+ assert.deepEqual(states, ['suspended', 'running']);
+ assert.equal(batches.reduce((sum, batch) => sum + batch.dropped, 0), 0);
+ assert.deepEqual(game.errors, []);
+ });
+});