How to Get the State of a Howl Object in Howler.js
In howler.js, retrieving the state of a Howl object is
essential for managing audio playback, updating user interfaces, and
handling loading sequences. This article explains how to determine both
the loading state and the playback state of a Howl instance
using its built-in methods and event listeners.
Checking the Loading State
To find out if your audio file is ready to play, use the
state() method. This method returns the current loading
status of the Howl instance as a string.
const sound = new Howl({
src: ['track.mp3']
});
// Retrieve the loading state
const currentState = sound.state();
console.log(currentState); // Outputs: 'unloaded', 'loading', or 'loaded'The three possible return values are: *
unloaded: The audio source has not been
loaded yet. * loading: The audio file is
currently being downloaded and decoded. *
loaded: The audio is fully loaded and
ready for playback.
Checking the Playback State
To determine if an audio source is currently active and making sound,
use the playing() method. This method returns a boolean
value.
// Check if any instance of this sound is playing
if (sound.playing()) {
console.log("Audio is currently playing.");
} else {
console.log("Audio is paused or stopped.");
}If you are playing multiple instances of the same sound, you can pass a specific sound ID to the method to check the state of that exact instance:
const soundId = sound.play();
// Check if the specific sound ID is playing
if (sound.playing(soundId)) {
console.log(`Sound instance ${soundId} is playing.`);
}Monitoring State Changes with Events
Instead of constantly polling the state of a Howl
object, you can register event listeners to react immediately when
states change.
const sound = new Howl({
src: ['track.mp3'],
onload: function() {
console.log('Finished loading! State is now: ' + this.state());
},
onloaderror: function(id, error) {
console.error('Loading failed: ' + error);
},
onplay: function(id) {
console.log(`Playback started for sound ID: ${id}`);
},
onpause: function(id) {
console.log(`Playback paused for sound ID: ${id}`);
},
onend: function(id) {
console.log(`Playback finished for sound ID: ${id}`);
}
});