once
once(
type: SoundEventsEnum,
callback: (event: SoundEvent) => void,
filter?: SoundEventFilter
): () => void;
Listen for the next matching event and then stop listening.
This is addEventListener for one-shot cases: waiting
for a track to finish before starting the next one, or for a fade to complete
before tearing something down. Doing that by hand means removing the listener
from inside itself, which is easy to forget. Forget it and the listener keeps
running for the rest of the session.
The returned function cancels the listener before it has fired, which is useful when a component unmounts while still waiting.
| Parameter | Type | Description |
|---|---|---|
type | SoundEventsEnum | The event to wait for |
callback | (event: SoundEvent) => void | Called once, then removed |
filter | SoundEventFilter (optional) | Narrows which sounds count. See addEventListener |
Returns a function that removes the listener.
Example
import { SoundHub, SoundEventsEnum } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSounds([
{ id: 'intro', url: '/audio/intro.mp3' },
{ id: 'theme', url: '/audio/theme.mp3' },
]);
// Play the theme as soon as the intro is done, and only then
soundHub.once(SoundEventsEnum.ENDED, () => {
soundHub.play('theme', { loop: true });
}, { soundId: 'intro' });
soundHub.play('intro');
Waiting for a fade
soundHub.once(SoundEventsEnum.FADE_OUT_COMPLETED, () => {
soundHub.unloadSound('level-1-music');
startNextLevel();
}, { soundId: 'level-1-music' });
soundHub.fadeOut('level-1-music', 2, undefined, 0, true);
Cancelling before it fires
const cancel = soundHub.once(SoundEventsEnum.ENDED, playNext, { soundId: 'track' });
// The user skipped ahead, so the natural end no longer matters
cancel();