Set up browser game audio the right way with the Web Audio API: one AudioContext, unlock on the first tap or key (including iOS), load and decode sound files once and cache them, pick a format each browser can play (Ogg, M4A, MP3), play buffers with volume, rate, loops and fades, pause with the tab, and the graph that the mixer, sound manager, positional audio and adaptive music build on. Inclu...
Download skill (.zip) Files on GitHubWeb audio development
The engine
import { createEngine } from "./engine.js"; // assets/engine.js
const audio = createEngine();
audio.unlockOn(window); // first pointerdown/keydown creates and resumes the context
audio.pauseWithPage(); // suspend when the tab is hidden
const { failed } = await audio.load({ jump: "sfx/jump", hit: "sfx/hit" }, (p) => bar.set(p));
audio.play("jump", { volume: 0.8, rate: 1.05 });
Paths without an extension get the first format the browser can play from formats (default ogg, m4a, mp3, wav). Ship
.m4a or .mp3 next to .ogg: older Safari can’t play Ogg.
Graph
sources -> (sound gain) -> mixer buses (game-audio-mixer) -> engine.output -> speakers
Everything connects to engine.output or to a mixer bus, never straight to ctx.destination, so one master control works.
The other audio skills take this engine: game-audio-mixer (buses and volumes), game-audio-management (sound pools and
limits), spatial-game-audio (position), adaptive-game-music (layers and sections).
Rules
- Unlock inside a gesture. Browsers block audio until the player taps or presses a key. Show a “tap to start” title screen.
- Decode once.
loadcaches buffers by name; play from memory. Use<audio>elements only for very long tracks you don’t want to decode (several minutes). - One context for the whole game. Creating one per sound runs out on Chrome.
- Short sounds as files of 0.05-2 s, trimmed of silence at the start so they play on time.
- Pause with the page and when the game pauses.
- Volumes on a curve:
sliderToGainmaps 0..1 sliders to decibels so the middle sounds half as loud.
Testing without a browser
assets/tests/fake-audio.mjs is a fake AudioContext: time moves only when you call ctx.advance(s), gains remember their
ramps (param.valueAt(t)), sources fire onended, and fakeFetch serves fake files. Use it to test volume logic,
limits and timing in node, then listen in the real preview.
Pitfalls
Starting audio before a gesture, a new AudioContext per sound, only Ogg files, new Audio() for every shot (slow, delayed,
limited on phones), sounds that keep playing in a hidden tab, and linear volume sliders.