Skip to content
Arnel Robles edited this page Oct 2, 2026 · 2 revisions

Sound

SoundManager plays short sounds through the Web Audio API. It can synthesize them, so no audio files are needed to start.

import { SoundManager } from 'dopaminejs';

const sound = new SoundManager();

button.addEventListener('click', () => sound.playSuccess());

Browsers keep audio suspended until the user interacts with the page. The first sound has to come from a click, tap or key press.

Config

Option Default Meaning
volume 1 Master volume, 0 to 1
customSounds none { key: url } map, same as calling registerSound for each
storageKey 'dopamineSoundsMuted' Where the mute flag is kept
storage localStorage, or memory Must be synchronous

The mute key is used as written. The DataService prefix does not apply to it.

Synthesized sounds

sound.playJump();
sound.playScore();
sound.playSuccess();
sound.playClick();
sound.playError();
sound.playGameOver();

sound.play('success');   // same thing by key

Each preset takes one argument, force. By default a preset plays the file loaded under its key, if there is one. Pass true to get the synth anyway. Nothing plays while muted.

A single tone:

sound.playTone(880, 0.15, 'square', 0.3);   // frequency Hz, seconds, waveform, volume

Waveform defaults to 'sine' and volume to 0.3.

Audio files

sound.registerSound('coin', '/audio/coin.mp3');
sound.registerSound('win', '/audio/win.mp3');

sound.play('coin');

Decoding needs an audio context, and the context only starts on the first play or playTone. Files registered before that are fetched when it starts. Files registered after are fetched at once.

preloadSounds({ key: url }) fetches a map and resolves when every file has settled. Since 2.4.0 it registers each key. Called before the audio context exists it resolves at once without fetching, and the files load when the context starts, as with registerSound. Before 2.4.0 the keys were not registered and a later play(key) did not find the sound.

play(key) looks for:

  1. a decoded file under that key
  2. a registered URL, which it loads and then plays
  3. the built-in synth, for jump, score, success, click, error and gameover

Any other key is silent. Registering a file under a built-in key replaces the synth for that key.

A file that fails to load (network error or a non-2xx status) is logged as a warning and does not throw.

Volume and mute

sound.setVolume(0.5);   // clamped to 0..1, NaN is ignored
sound.getVolume();
sound.toggleMute();     // returns the new state and saves it

Without Web Audio

initAudio() returns false when the browser has no Web Audio. play and playTone then do nothing. Nothing throws.

Cleanup

sound.destroy();

Cancels queued tones, closes the audio context and drops the decoded files.

Related

Clone this wiki locally