How to Get Audio Duration in Howler.js
This article explains how to retrieve the duration of an audio file using the Howler.js library. You will learn the exact method to use, how to handle asynchronous audio loading to prevent receiving a duration of zero, and how to implement this in a practical JavaScript example.
To get the duration of an audio file in Howler.js, you use the
.duration() method on your Howl instance. This
method returns the duration of the audio source in seconds.
The Loading Challenge
Because audio files load asynchronously, calling
.duration() immediately after instantiating a new
Howl object will return 0. To get the correct
duration, you must wait until the audio file has fully loaded.
Using the onload Event
The most reliable way to get the duration is by using the
onload callback option when creating your Howl
instance, or by binding to the load event.
Here is the standard implementation:
// Create a new Howl instance
const sound = new Howl({
src: ['audio.mp3'],
html5: true, // Use HTML5 Audio to handle large files
onload: function() {
// This code runs once the audio is fully loaded
const durationInSeconds = sound.duration();
console.log('Audio duration: ' + durationInSeconds + ' seconds');
}
});Alternative: Event Listener Binding
If you prefer to define your event listeners separately from the
initial configuration, you can use the .on() method:
const sound = new Howl({
src: ['audio.mp3']
});
sound.on('load', function(){
const durationInSeconds = sound.duration();
console.log('Audio duration: ' + durationInSeconds + ' seconds');
});Checking the Load State
If you need to check the duration dynamically later in your code (for example, when a user clicks a button), you should check if the audio state is loaded first:
function checkDuration() {
if (sound.state() === 'loaded') {
console.log('Duration: ' + sound.duration() + 's');
} else {
console.log('Audio is still loading...');
}
}