Skip to content

Fix iOS/Android audio delay and improve sound layering - #26

Merged
john-doherty merged 1 commit into
masterfrom
ios-sounds-fix
Aug 6, 2026
Merged

Fix iOS/Android audio delay and improve sound layering#26
john-doherty merged 1 commit into
masterfrom
ios-sounds-fix

Conversation

@john-doherty

Copy link
Copy Markdown
Contributor

On iOS Safari, AudioContext is suspended at page load and can only be resumed on a user gesture. The previous code called audioCtx.resume() inside playSound() - but since resume() is async, the first sound after a gesture was delayed by 50–200ms. iOS also re-suspends audio after phone calls, Siri, or app switching, and there was no recovery for that.

Additionally, playSound always stopped any existing instance before playing, so rapid collisions (bricks, bullets) would cut each other off instead of overlapping.

Changes

  • _unlockAudio() - one-shot listener on touchstart/pointerdown/mousedown/keydown that calls audioCtx.resume() and plays a silent 1-sample buffer to warm the iOS audio graph, then removes itself
  • visibilitychange + focus listeners - resume AudioContext when the page regains visibility, covering iOS interruptions
  • playSound reworked - short SFX now allow up to 3 overlapping instances; the 4th evicts the oldest. Pass { loop: true } or { restart: true } to get the old single-instance behaviour. Fallback resume() kept as a safety net
  • README updated - the previous description ("calling playSound twice restarts it") was incorrect for SFX; now correctly describes the overlap-up-to-3 behaviour
  • Sound tests expanded - 4 new behavioural tests covering rapid play, cap eviction, loop restart, and stop after multiple plays

@john-doherty john-doherty self-assigned this Aug 6, 2026
@john-doherty
john-doherty merged commit 5511edc into master Aug 6, 2026
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant