Skip to main content

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​

ParameterTypeDefaultDescription
soundsToLoad{ id: string; url: string | string[] }[]requiredThe sounds to load. Each url may be a list of alternatives, and the browser picks the first format it can play.
signalAbortSignalnoneSignal 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​

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​

  • Sounds are loaded in batches of maxParallelLoads (default 10, a SoundHubConfig option). 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 getLoadState to see which ids made it.
  • Ids that are already loaded are skipped without a fetch.
  • Every sound dispatches its own loading and loaded events. Failures are logged, stored for getLastError and dispatched as error events. An AbortError is 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.