Skip to main content

registerSound

Write down where a sound lives without fetching it. Use it for audio you know about but do not need at startup, such as the boss music or the sounds of a later level.

registerSound(id: string, url: string | string[]): void;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredThe id you will address the sound by.
urlstring | string[]requiredWhere the file lives. A list of alternatives lets the browser pick the first format it can play when the sound is loaded.

Returns​

Nothing.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();

soundHub.registerSound('boss-music', ['/audio/boss.opus', '/audio/boss.mp3']);
soundHub.getLoadState('boss-music'); // 'unloaded'

// Later, when the moment arrives: no url needed
await soundHub.loadSound('boss-music');
soundHub.play('boss-music', { loop: true });

Good to know​

  • Nothing is fetched. Only loadSound (or loadSounds) starts a request, and with a list of urls only the chosen file is fetched.
  • Playing a sound that is registered but not loaded is an error, the same as playing an id the hub has never heard of. Load it first, or check getLoadState.
  • Registering an id again replaces its url list. For an id that is not loaded, the load state goes back to unloaded, which also clears an earlier error.
  • An empty url, or a list without any usable string, is ignored. Only a debug message is logged.
  • Added in 6.2.0.

See also​