How to Listen for the End Event in Howler.js

This article explains how to detect when an audio track finishes playing using the Howler.js JavaScript library. You will learn how to trigger specific actions upon playback completion by utilizing the built-in onend event listener, both during the initialization of your audio object and dynamically during runtime.

Method 1: Using the onend Callback During Initialization

The most common way to listen for the end of a track is by defining the onend property directly inside the Howl configuration object when you instantiate your sound.

const sound = new Howl({
  src: ['track.mp3'],
  onend: function() {
    console.log('The track has finished playing!');
    // Trigger your next action here, such as playing the next song
  }
});

// Play the sound
sound.play();

Method 2: Registering the Event Dynamically with .on()

If you need to add or change the end event listener after the Howl object has already been created, you can use the .on() method. This is useful for dynamically chaining events or changing behavior based on user interaction.

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

// Bind the 'end' event dynamically
sound.on('end', function() {
  console.log('Playback finished (dynamically bound).');
});

sound.play();

Handling Specific Playbacks with Sound IDs

Howler.js allows you to play multiple instances of the same sound. The onend callback automatically passes the unique id of the finished sound instance as its first argument. You can use this ID to determine exactly which playback instance just completed.

const sound = new Howl({
  src: ['track.mp3'],
  onend: function(id) {
    console.log(`Sound instance with ID ${id} has finished.`);
  }
});

// Play multiple instances of the same sound
const id1 = sound.play();
const id2 = sound.play();