Repository navigation
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.
| 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.
sound.playJump();
sound.playScore();
sound.playSuccess();
sound.playClick();
sound.playError();
sound.playGameOver();
sound.play('success'); // same thing by keyEach 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, volumeWaveform defaults to 'sine' and volume to 0.3.
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:
- a decoded file under that key
- a registered URL, which it loads and then plays
- the built-in synth, for
jump,score,success,click,errorandgameover
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.
sound.setVolume(0.5); // clamped to 0..1, NaN is ignored
sound.getVolume();
sound.toggleMute(); // returns the new state and saves itinitAudio() returns false when the browser has no Web Audio. play and playTone then do nothing. Nothing throws.
sound.destroy();Cancels queued tones, closes the audio context and drops the decoded files.
- Plugin: Howler Audio: music, loops, sprites and formats through Howler.
-
Plugin: Sound Packs: tone definitions you can feed to
playTone.
Start
Progression
Engine
Packages
Reference