Audio Manager
Music and sound effects on separate volume channels, with mute, fades, music crossfades and ducking. It waits for the first tap or key press, as browsers require, before making any sound.
Files: audio-manager.js (the component, no dependencies) and audio-manager.test.mjs (6 tests).
Copy audio-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createAudio } from "./audio-manager.js";
const audio = createAudio();
audio.autoUnlock(); // starts sound on the first tap or key press
await audio.load({ jump: "assets/sfx/jump.ogg", theme: "assets/music/theme.ogg" });
audio.play("jump", { volume: 0.8, rate: 0.95 + Math.random() * 0.1 });
audio.playMusic("theme", { fade: 1 }); // waits for unlock if needed
audio.setVolume("music", 0.5);
API
createAudio({ context, buses, fetch }) → audiobuses default to [“music”, “sfx”, “ui”, “voice”]; all feed “master”audio.unlock(waitMs = 1000)resume the AudioContext (call from a tap or key press); resolves true or false, never hangsaudio.autoUnlock(target)unlock on the first tap, click or key pressaudio.unlockedtrue once sound can playaudio.load({ name: url })fetch and decode; resolves to { loaded, failed }audio.add(name, audioBuffer)use a buffer you already haveaudio.play(name, { bus, volume, rate, loop, offset }) → { stop(fade), source } or null if locked or missingaudio.playMusic(name, { fade, volume, loop }) crossfade to a new track; same track again does nothingaudio.stopMusic(fade)audio.setVolume(bus, 0..1) / audio.volume(bus)perceptual curve (value squared), “master” includedaudio.mute(bus, on) / audio.isMuted(bus)audio.duck(bus, amount, seconds)dip a bus (e.g. music under a voice line) then returnaudio.volumes() / audio.setVolumes(obj)for saving with the Settings Manager
audio.context, audio.missing (names asked for but not loaded)
Engines
| Engine | Notes |
|---|---|
| Vanilla | yes. |
| Phaser | yes, instead of Phaser’s sound system (turn it off with audio: { noAudio: true }) or alongside it with its own volume. |
| PixiJS | yes (Pixi has no built-in audio). |
| Three.js | yes. Pass audio.context to THREE.AudioContext.setContext() to share one context for positional audio. |
Tests
Node tests with a fake AudioContext: locked until unlock, music waits for unlock, bus volumes and mute, crossfade, ducking, missing sounds, failed loads.
Run them with node --test toolkit/components/audio-manager/ (Node 20 or newer, nothing to install).