loadSounds
Load several sounds in one call. The fetches run in parallel, in batches, which is what you want for the sounds a game or an app needs at startup.
loadSounds(soundsToLoad: { id: string; url: string | string[] }[], signal?: AbortSignal): Promise<void>;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
soundsToLoad | { id: string; url: string | string[] }[] | required | The sounds to load. Each url may be a list of alternatives, and the browser picks the first format it can play. |
signal | AbortSignal | none | Signal from an AbortController to cancel every load that has not finished. |
Returns
Promise<void>: resolves when every sound is loaded. It rejects with an error naming the ids that failed, or with an AbortError when the signal fires.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSounds([
{ id: 'music', url: '/audio/theme.mp3' },
{ id: 'click', url: ['/audio/click.opus', '/audio/click.mp3'] },
{ id: 'rain', url: '/audio/rain.mp3' },
]);
soundHub.play('music', { loop: true });
Cancelling the loads
const controller = new AbortController();
soundHub.loadSounds([
{ id: 'music', url: '/audio/theme.mp3' },
{ id: 'click', url: '/audio/click.mp3' },
], controller.signal).catch((err) => {
if (err.name !== 'AbortError') throw err;
});
// When the component unmounts
controller.abort();
Try it
Load, play and unload
IdleSounds
- helicopternot loaded
- tokyo-trainnot loaded
- bells-melodynot loaded
- techno-tunenot loaded
Load one sound with loadSound or several with loadSounds. A loaded sound plays at once; unloadSound frees its buffer.
Code
Your clicks show up here as soundhub calls
Good to know
- Sounds are loaded in batches of
maxParallelLoads(default 10, aSoundHubConfigoption). The next batch starts when the previous one has settled. - When a sound in a batch fails, the rest of that batch still loads, but the promise rejects and later batches are not started. Check
getLoadStateto see which ids made it. - Ids that are already loaded are skipped without a fetch.
- Every sound dispatches its own
loadingandloadedevents. Failures are logged, stored forgetLastErrorand dispatched aserrorevents. AnAbortErroris passed on without logging. - An empty list resolves at once.
See also
loadSound: load one sound, with the same options per sound.registerSounds: record the urls now and load them later.loadStream: for long files that should not be decoded up front.