How to Trigger an Event When Sound Stops in Howler.js
In this article, you will learn how to detect and trigger a specific
action or event when a sound finishes playing or is programmatically
stopped in the Howler.js library. We will cover the built-in event
listeners provided by Howler.js—specifically focusing on the
end and stop events—and provide clear code
examples to implement them in your JavaScript projects.
Using Callbacks at Initialization
The most straightforward way to trigger an event is by defining the
onend or onstop callbacks directly within the
configuration object when you instantiate your Howl
sound.
const sound = new Howl({
src: ['audio.mp3'],
// Triggered when the sound naturally finishes playing
onend: function() {
console.log('The sound has finished playing naturally.');
// Trigger your event/function here
},
// Triggered when sound.stop() is called programmatically
onstop: function() {
console.log('The sound was stopped manually.');
// Trigger your event/function here
}
});Binding Events Dynamically
with .on()
If you need to bind these events after the sound object has already
been created, you can use the .on() method. This is useful
if you want to add or change event handlers dynamically.
const sound = new Howl({
src: ['audio.mp3']
});
// Bind the stop event
sound.on('stop', function() {
console.log('Event triggered: Sound has been stopped.');
});
// Bind the end event
sound.on('end', function() {
console.log('Event triggered: Sound finished playing.');
});Understanding
the Difference Between stop and end
When working with audio events in Howler.js, it is important to distinguish between these two states:
end: This event only fires when the audio track plays all the way to its end without interruption.stop: This event only fires when you explicitly callsound.stop()in your JavaScript code.
If you want to trigger the exact same event regardless of whether the sound stopped naturally or was stopped manually, you should bind your function to both events:
function handleSoundStopped() {
console.log('Audio playback has ceased.');
}
// Bind the same handler to both events
sound.on('end', handleSoundStopped);
sound.on('stop', handleSoundStopped);