Manage sound playback in a busy game: named sounds with several variations that never repeat twice in a row, random pitch and volume, per-sound voice limits and cooldowns so twenty coins don't make one loud blast, a global voice cap where important sounds steal from unimportant ones, loops with fades, tags to stop groups of sounds when a scene or character ends, per-scene loading and unloading,...
Download skill (.zip) Files on GitHubGame audio management
import { createEngine } from "./engine.js";
import { createMixer } from "./mixer.js"; // from game-audio-mixer (optional)
import { createSounds } from "./sounds.js"; // assets/sounds.js (engine.js is included)
const engine = createEngine(); const sfx = createSounds(engine, { mixer: createMixer(engine), maxVoices: 24 });
sfx.defineAll({
step: { files: ["sfx/step1", "sfx/step2", "sfx/step3"], pitchVar: 0.08, maxVoices: 2, cooldown: 0.08, priority: 1 },
coin: { files: ["sfx/coin"], maxVoices: 3, cooldown: 0.04, priority: 4 },
alarm: { files: ["sfx/alarm"], priority: 9, bus: "ui" },
rain: { files: ["sfx/rain"], priority: 2, bus: "sfx" },
});
await sfx.preload(["step", "coin", "alarm"]);
sfx.play("coin"); sfx.loop("rain", { fade: 1 }); sfx.play("step", { tags: ["player"] });
Settings per sound
| Setting | Default | Use |
|---|---|---|
| files | [name] | variations; one is picked at random, never the same twice in a row |
| pitchVar, volVar | 0.05, 0.08 | random spread so repeats don’t sound robotic |
| maxVoices | 4 | at the limit the oldest copy stops (steal: "none" skips instead) |
| cooldown | 0.03 s | ignore repeats closer than this |
| priority | 5 | at the global cap, a sound steals the oldest lower-priority voice, or is skipped |
| bus | sfx | mixer bus |
| tags | [] | groups for stopTag |
Priorities: warnings and player damage 8-10, the player’s own actions 5-7, enemies 3-5, footsteps and ambience 1-2.
Lifecycle
- Scene starts:
preloadits sounds (show progress). Scene ends:stopTag("level"), stop its loops,unloadbig ones. - Pause:
stopTagshort sounds or suspend the engine; keep loops paused, not restarted. - Debug: show
sfx.stats()(active voices, skipped, stolen) in a dev overlay.
Pitfalls
One file per sound (repeats sound fake), no limits (coin showers clip), important sounds lost under noise, loops that keep running after the scene, and loading every sound for every level up front.