How to Get Active Sounds in Howler.js

This article explains how to determine the number of active, currently playing audio sources in Howler.js. You will learn how to count active sounds for both a specific Howl instance and globally across all sound instances in your application.

Counting Active Sounds for a Specific Howl Instance

Howler.js allows a single Howl instance to play multiple overlapping sounds simultaneously, with each playback assigned a unique sound ID. To find the number of active (playing) sounds for a specific instance, you can iterate through its internal _soundIds array and check the playing status of each ID using the playing(id) method.

Here is the code to achieve this:

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

// Play multiple instances
sound.play();
sound.play();

// Get the number of active playing sounds for this instance
const activeSoundsCount = sound._soundIds.filter(id => sound.playing(id)).length;

console.log(`Active sounds for this instance: ${activeSoundsCount}`);

Counting Active Sounds Globally

If you need to find the total number of active sounds playing across your entire application, you can query the global Howler object. Howler.js keeps track of all active Howl instances in the Howler._howls array.

By combining the global list of instances with the individual instance check, you can calculate the total active sound count:

function getGlobalActiveSoundsCount() {
  let totalActive = 0;

  // Loop through all active Howl instances
  Howler._howls.forEach(howl => {
    howl._soundIds.forEach(id => {
      if (howl.playing(id)) {
        totalActive++;
      }
    });
  });

  return totalActive;
}

// Example usage
console.log(`Total active sounds playing globally: ${getGlobalActiveSoundsCount()}`);