Get Audio ID of Playing Sound in Howler.js
This article explains how to retrieve the unique audio ID of a playing sound in Howler.js. You will learn how to capture this ID during playback initiation and through event listeners, allowing you to target and control individual sound instances programmatically.
In Howler.js, a single Howl object can play multiple
instances of the same sound simultaneously. To manipulate a specific
instance—such as pausing, stopping, or changing its volume—you must use
its unique sound ID.
Method 1: Capture
the ID from the .play() Method
The most direct way to get the audio ID is to capture the return
value of the .play() method. When called,
.play() immediately returns the unique integer ID for that
specific playback instance.
const sound = new Howl({
src: ['audio.mp3']
});
// Capture the unique ID when playing the sound
const soundId = sound.play();
console.log("Playing Sound ID:", soundId);Method 2: Use the ‘play’ Event Listener
If you cannot capture the ID directly at the moment of calling
.play(), you can listen to the 'play' event.
Howler.js automatically passes the unique sound ID as the first argument
to the event listener’s callback function.
const sound = new Howl({
src: ['audio.mp3']
});
// Set up the event listener to capture the ID
sound.on('play', (id) => {
console.log("Sound started playing with ID:", id);
});
// Trigger the playback
sound.play();Controlling the Specific Instance
Once you have retrieved the sound ID using either method, you can pass it as an argument to other Howler.js methods to control only that specific audio instance, leaving other playing instances of the same sound unaffected.
// Pause only the specific sound instance
sound.pause(soundId);
// Change the volume of only this specific instance
sound.volume(0.5, soundId);