Skip to content

Sounds

Sounds loads sound files by name and plays them through the Web Audio API. Each file is decoded once, and every play() starts a new copy straight away, so the same sound can overlap itself. Game loads the sound definitions and exposes the shared service as services.sounds. Breakout makes its own sounds in globals.js instead. For music that loops and switches between screens, use Music, which plays through Sounds.

const { sounds } = this.game;
sounds.play(SoundName.Confirm);

Define the sounds once, usually in src/assets.js:

const soundDefinitions = [
{ name: SoundName.Confirm, path: './assets/sounds/confirm.wav', volume: 0.6 },
{
name: SoundName.BrickHit,
path: './assets/sounds/brick-hit.wav',
size: 10,
volume: 0.5,
},
];
flowchart LR
	A[SoundDefinition] --> B[Sounds.load]
	B --> C[Fetch and decode the file once]
	D["sounds.play(name)"] --> E{"Has the player clicked\nor pressed a key yet?"}
	E -- no --> F[Skip the sound]
	E -- yes --> G{Fewer than size copies playing?}
	G -- no --> F
	G -- yes --> H[Start a new copy]
sounds.load(soundDefinitions);

Starts fetching and decoding every file, and stores each one under definition.name.

Definition field Meaning
name Stable key used by play(), stop(), and get(). Use a SoundName value so a typo shows up in the editor.
path URL of the audio file.
volume Per-sound volume from 0 (silent) to 1 (full volume).
size Optional; the most copies that can play at once. Leave it out and copies overlap freely.
loop Optional; when true, the sound repeats until stop() and only ever plays one copy. Defaults to false.
sounds.play(SoundName.PaddleHit);

Starts a new copy of the sound and returns it. It returns null and plays nothing if the file hasn’t loaded yet, if the player hasn’t clicked or pressed a key yet, or if size copies are already playing.

A looping sound only ever plays one copy, so asking for it again leaves the one copy playing. That makes it safe to call every frame, which is how Breakout’s title screen starts its music on the first key press.

await sounds.playAsync(SoundName.LevelUp);

Plays the sound and returns a promise that resolves when it finishes. If the sound couldn’t start, the promise resolves straight away, so nothing waiting on it can hang.

sounds.stop(MusicName.Invincible);

Stops every copy of the sound that’s playing.

const { buffer } = sounds.get(MusicName.PlayerDown);
const seconds = buffer?.duration;

Returns the loaded sound: its decoded buffer (null until it has loaded), a loaded promise that resolves once it has, the copies playing now, and its size, volume, and loop. It throws Unknown sound: <name> if no matching definition was loaded.