How to Check if Sound is Loaded in Howler.js

This article explains how to determine if an audio file is currently loaded into memory using the Howler.js library. You will learn how to use the state() method to check the loading status of a Howl instance synchronously, as well as how to listen for load events asynchronously.

In Howler.js, the most direct way to check if a sound is loaded into memory is by calling the state() method on your Howl instance. This method returns a string representing the current loading state of the audio source.

Using the state() Method

The state() method returns one of three string values: * 'unloaded': The sound has not been loaded yet, or it has been explicitly unloaded from memory. * 'loading': The sound is currently downloading and buffering. * 'loaded': The sound is fully loaded into memory and ready to play.

Here is a basic code example demonstrating how to check this state:

const sound = new Howl({
  src: ['audio.mp3']
});

// Check the current loading state
if (sound.state() === 'loaded') {
  console.log('The sound is loaded and ready to play.');
} else if (sound.state() === 'loading') {
  console.log('The sound is still loading.');
} else {
  console.log('The sound is unloaded.');
}

Handling Loading Asynchronously

Because audio loading is an asynchronous process, checking the state immediately after instantiation will usually return 'loading'. To execute code the exact moment the sound finishes loading, you should register a listener for the load event.

const sound = new Howl({
  src: ['audio.mp3']
});

// Define a function to run once loaded
sound.on('load', function() {
  console.log('Sound loaded successfully!');
  // You can safely query sound.state() here, which will return 'loaded'
});

// Define a function to handle load errors
sound.on('loaderror', function(id, error) {
  console.error('Failed to load sound:', error);
});