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
| Parameter | Type | Default | Description |
|---|---|---|---|
id | string | required | ID 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
stoppedevent even if it was not playing. Then anunloadedevent 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:2and 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
unloadedevent 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
removeSound: unload and forget the url as well.updateSoundUrl: swap the file behind an id.getLoadState: check whether a sound is loaded.