Skip to main content

getLoadState

Get where a sound is in the loading process. isSoundLoaded is the quick yes or no; this is the answer when you want to show a spinner or a retry button.

getLoadState(id: string): SoundLoadState;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of the sound or stream.

Returns​

SoundLoadState, one of 'unloaded' | 'loading' | 'loaded' | 'error':

StateMeaning
unloadedThe hub has never heard of this id, it was registered with registerSound and not fetched yet, or it was unloaded.
loadingA fetch is in flight.
loadedThe audio is decoded and ready to play, or the id is a stream.
errorThe fetch or the decode failed. The url is still on file, so you can try again.

An unknown id gives 'unloaded'.

Example​

import { SoundHub, SoundEventsEnum } from 'soundhub';

const soundHub = new SoundHub();

soundHub.registerSound('music', '/audio/theme.mp3');
soundHub.getLoadState('music'); // 'unloaded'

const loading = soundHub.loadSound('music');
soundHub.getLoadState('music'); // 'loading'

await loading;
soundHub.getLoadState('music'); // 'loaded'

A loading event is dispatched when a fetch starts and loaded when it finishes, so a spinner does not have to poll:

soundHub.addEventListener(SoundEventsEnum.LOADING, (event) => {
spinner.show(event.soundId);
});

soundHub.addEventListener(SoundEventsEnum.LOADED, (event) => {
spinner.hide(event.soundId);
});

Good to know​

  • A stream loaded with loadStream reports loaded once the browser has its metadata. Before that it reports unloaded, because streams have no loading state.
  • unloadSound, removeSound and reset with unloadSounds: true put a sound back to unloaded. Before 6.4.0 the reset left it at loaded.
  • Retrying after error is a plain loadSound(id): the url list is kept.
  • Added in 6.2.0.

See also​