loadSound
Fetch one audio file, decode it into memory and store it under an id. After the promise resolves the sound can be played straight away. Use loadSounds for several at once.
loadSound(id: string, url?: string | string[], signal?: AbortSignal): Promise<void>;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | The id you will address the sound by. |
url | string | string[] | the registered url | Url or path of the file. A list of alternatives lets the browser pick the first format it can play. Leave it out for a sound that was registered with registerSound. |
signal | AbortSignal | none | Signal from an AbortController to cancel the load. |
Returns
Promise<void>: resolves when the sound is decoded and stored. It rejects when the load fails, when there is no url at all, or with an AbortError when the signal fires.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');
soundHub.play('music', { loop: true });
One sound, several formats
Hand it a list and the browser picks the first format it can play. The check runs before anything is fetched, so the files it cannot use are never requested:
await soundHub.loadSound('music', [
'/audio/theme.opus', // Chrome, Firefox, Edge
'/audio/theme.m4a', // Safari
]);
A url without a known extension, a signed CDN link for example, is not ruled out. When none of the urls has an extension the browser is known to play, the first one is used.
A sound that was registered earlier
soundHub.registerSound('boss-music', '/audio/boss.mp3');
// later, when the level starts
await soundHub.loadSound('boss-music');
Cancelling a load
const controller = new AbortController();
soundHub.loadSound('rain', '/audio/rain.mp3', controller.signal)
.catch((err) => {
if (err.name !== 'AbortError') throw err;
});
// When the component unmounts
controller.abort();
Try it
Load, play and unload
Idle- 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.
Good to know
- An id that is already loaded is skipped: nothing is fetched and the promise resolves. To swap the file use
updateSoundUrl, orunloadSoundfirst. - A
loadingevent is dispatched when the fetch starts and aloadedevent (withduration,bufferSize,fileSize,sampleRateandchannels) when the sound is ready.getLoadStatefollows along. - Each fetch is retried (
fetchRetries, default 2) and times out afterfetchTimeoutseconds (default 8). When Web Audio loading fails, the HTML5 Audio fallback is tried. Files larger thanmaxAudioSize(default 50 MB) are refused. All of these areSoundHubConfigoptions. - A failed load is logged, stored for
getLastError, dispatched as anerrorevent and leaves the load state aterror. AnAbortErroris passed on as it is, without logging or anerrorevent. - The whole list of urls is remembered, so
getSoundUrlsreturns it and a laterloadSound(id)without a url can pick again. The list form arrived in 6.2.0.
See also
loadSounds: load a batch of sounds in parallel.loadStream: play a long file without decoding it first.registerSound: record a url now and load it later.canPlay: ask whether the browser plays a format.addBuffer: add audio you already have in memory, without a url.