Web audio unlock on mobile stops sounds
My game's mobile audio unlock ran on every tap and paused whatever was playing. The fix, the tests, and the counter that missed the bug the first time.
Contents
Finishing a row in ASMR Logo Craft Block plays a small celebration. The four tiles light up one after another, each with a chime a step higher than the last, then they fuse into a banner that flies up with a whoosh. Playing it on the Android emulator, I kept moving tiles during the celebration, and the chimes stopped dead the moment my finger touched another tile.
The cause was the web audio unlock, the code that lets a mobile WebView play sound at all. It ran on every tap, and every time it ran it paused and rewound sounds that were playing. This post is that bug, the fix, and the counter I wrote to prove it, which reported zero problems on the broken version the first two times I ran it.
The setup
The game is React 19 and Vite inside a Capacitor 8 Android app. Sounds are short mp3 clips —
move, land-soft, land-hard, chime-1 to chime-4, a whoosh, a win sound — played
through a small sound package shared by my games. On Android and on the web, that package
plays HTML <audio> elements in the WebView. On iOS it hands the clip to a native player
instead.
Each sound key gets a pool of <audio> elements, three made up front and up to five, so a
chime can start again while the last copy is still ringing. To play a sound, the package
takes the first element in the pool that is paused or has ended.
Mobile browsers and WebViews will not play sound until the player has touched the page, so
the package also has an unlock function. The game called it from the tile's pointerdown
handler, because a tile touch is a user gesture and the first one is the earliest chance to
unlock.
That handler runs on every touch, not just the first.
Why the unlock stopped the sound
The unlock did the usual trick: play each sound once, silently, inside the gesture, so the browser marks it as allowed. Simplified, and not the package's actual code:
// Simplified example of the old unlock: runs on EVERY pointerdown.
function unlockAudio() {
for (const pool of pools.values()) {
const clip = pool[0];
const volume = clip.volume;
clip.volume = 0;
clip.play()
.then(() => { clip.pause(); clip.currentTime = 0; clip.volume = volume; })
.catch(() => { clip.volume = volume; });
}
}
Run once, on the first touch, this is harmless: nothing is playing yet. Run on a later touch,
it reaches into every pool and takes pool[0], which is the element the play function picks
first, and so usually the one making a sound. Setting its volume to zero silences it on the
spot. The play() call on it succeeds, since it is playing already, and then pause() and
currentTime = 0 finish the job.
So one tap during a celebration muted, paused and rewound the chime in flight, plus the move and landing sounds from the drop that finished the row. On iOS the function returns before any of this, because the native player needs no unlock, so the bug lived on Android and on the web only.
The first thing I checked was whether it was the sound at all. The report was "the effect
stops", which could mean the banner. Taking a snapshot of every running animation with
document.getAnimations() before, during and after a touch and drag showed the banner's
flight animation in all three. The visuals kept going; the sound was what stopped.
Unlock once and leave playing sounds alone
The fix has two parts, and either one alone would have stopped the cut:
// Simplified example of the fix.
let unlocked = false;
function unlockAudio() {
if (unlocked) return; // the gesture is only needed once
unlocked = true;
for (const pool of pools.values()) {
const clip = pool.find((c) => c.paused); // never a clip that is playing
if (!clip) continue;
// ...same silent play, pause, rewind as before
}
}
The flag makes the unlock a one-time event, which is all the browser's rule asks for. The
find covers what the flag cannot: a sound that is already playing when the first unlock
runs. An element that is playing is already unlocked, so it has nothing to gain from the trick
and everything to lose.
The game still calls the unlock on every tile pointerdown. After the first touch that call
returns at once.
Two tests that fail on the old code
Two tests went into the sound package with the fix, and both failed on the previous version before passing on the new one:
- It never stops a sound that is playing. Register a chime, unlock, play the chime, spy on
pause, unlock again, and expect no pause. - It unlocks once, however many taps call it. Unlock three times and expect one
play().
The package's 24 tests and the game's 1,845 all passed with the fix in, and the patch release went out through the package's normal CI.
The counter that could not see the bug
Tests on a fake <audio> prove the logic. I also wanted to hear it fixed, or the nearest
thing a script can do: solve a row on the Android emulator, tap tiles during the light-up and
the banner flight, and list every sound that got cut.
The first counter wrapped HTMLMediaElement.prototype.pause and counted a pause on an element
that was playing at a volume above zero. It reported zero cuts for the fixed version, which was
expected. It also reported zero for the old version in a desktop browser, and zero again on the
emulator, which was not.
The reason was in the bug itself. The unlock sets the volume to zero before it pauses. By the
time my wrapper saw the pause(), the clip was at volume zero, so my "audible" test said it
was silent and let it go. The counter was blind to exactly the thing it was written to catch.
The second version decides whether a clip is audible when it starts, not when it stops:
// Injected into the WebView before the test taps.
window.cut = [];
const { play, pause } = HTMLMediaElement.prototype;
HTMLMediaElement.prototype.play = function () {
if (this.volume > 0) this.audible = true;
return play.call(this);
};
HTMLMediaElement.prototype.pause = function () {
if (this.audible && !this.paused && !this.ended) window.cut.push(this.src.split('/').pop());
this.audible = false;
return pause.call(this);
};
Same emulator, same script, the only change being the version of the sound package built into the APK:
old: sounds cut by touches: ["chime-1.mp3","chime-2.mp3","chime-3.mp3","chime-4.mp3","move.mp3","land-soft.mp3","land-hard.mp3"]
new: sounds cut by touches: []
All four chimes, plus the move and landing sounds. Nothing on the fixed build.
I have written before about checks that pass while broken, and the lesson is the same one: a measurement that has only ever said "fine" has not been tested yet. Running it against the old code is what found the hole. Had I only run it on the fixed build, I would have shipped a green result that meant nothing.
The other audio bug in the same celebration
Earlier, in the version of the same game from before it moved to the shared sound package, the same moment had a different audio problem: a freeze. Its sounds were synthesised live with the Web Audio API, and recording frame times in headless Chromium at phone size showed one frame of 264 ms shortly after a row was solved, just as the banner started to fly.
A CPU profile of that moment put 245 ms between the row being solved and two frames later, and
211 ms of it on one line of the sound hook: new AudioContext(). Each component that played
sounds created its own AudioContext the first time it needed one, and the profile caught one
of those being created in the middle of the solve.
The fix was one shared context for the whole app, created and resumed on the first
pointerdown or touchstart anywhere, before any animation needs it. The same measurement
dropped from 245 ms to 34 ms, and the solve recording had no long frames. That was measured in
a desktop browser, not on a phone, so I can say the stall was real and gone there; how long it
was on a device I never measured.
Both fixes ended up in the same place: the first touch. Set the audio up once, early, inside a gesture, and leave it alone after that.
What I would check in any mobile web game
- Find where the unlock is called. If it is inside a handler that runs on every touch, it has to be safe to run on every touch. Mine was not.
- Check what the unlock touches. If it reuses elements that the game also plays, it can stop them. A guard against already-playing elements costs one line.
- Count
new AudioContext()calls. Creating one cost 211 ms in my profile, and a context made lazily gets made at the worst moment, the first time something needs a sound. - Run your probe on the broken build first. If it cannot see the bug you already know is there, it will not see the next one either.
The sound fix did not end the report, by the way. Grabbing a tile and holding it straight after a solve still froze the celebration. That turned out to be a separate cause in the board code, which put the celebration off while a finger was down, and it had nothing to do with audio.