Skip to main content

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​

ParameterTypeDefaultDescription
idstringrequiredThe id you will address the sound by.
urlstring | string[]the registered urlUrl 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.
signalAbortSignalnoneSignal 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​

Try it

Load, play and unload

Idle
Sounds
  • 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​

  • An id that is already loaded is skipped: nothing is fetched and the promise resolves. To swap the file use updateSoundUrl, or unloadSound first.
  • A loading event is dispatched when the fetch starts and a loaded event (with duration, bufferSize, fileSize, sampleRate and channels) when the sound is ready. getLoadState follows along.
  • Each fetch is retried (fetchRetries, default 2) and times out after fetchTimeout seconds (default 8). When Web Audio loading fails, the HTML5 Audio fallback is tried. Files larger than maxAudioSize (default 50 MB) are refused. All of these are SoundHubConfig options.
  • A failed load is logged, stored for getLastError, dispatched as an error event and leaves the load state at error. An AbortError is passed on as it is, without logging or an error event.
  • The whole list of urls is remembered, so getSoundUrls returns it and a later loadSound(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.