Skip to main content

unloadSound

Stop a sound and drop it from the hub so its decoded audio can be freed. The url stays on file, so loadSound(id) without a url brings it back. Use it to free memory between levels or screens.

unloadSound(id: string): void;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of the sound or stream to unload.

Returns​

Nothing.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');

soundHub.play('music');

// Leaving the level
soundHub.unloadSound('music');
soundHub.isSoundLoaded('music'); // false
soundHub.getLoadState('music'); // 'unloaded'

// Coming back: the url is still known
await soundHub.loadSound('music');

Good to know​

  • A buffered sound is stopped first, which dispatches a stopped event even if it was not playing. Then an unloaded event follows.
  • It also takes the sound out of its group, resets its instance counter and removes event listeners that were added with an { instanceId: id } filter.
  • Overlapping instances (music:1, music:2 and so on) and sprite sounds are separate entries and are not unloaded with the base id.
  • For a stream it pauses the media element, disconnects it and clears its source so the browser stops downloading. Only the unloaded event is dispatched. If the stream was on the Media Session, that is cleared too.
  • An id that is not loaded is ignored, with only a debug message.

See also​