Learn how to obtain the duration of an audio file in the browser using JavaScript.

How to retrieve the duration of a MP3/WAV Audio File in the Browser with JavaScript

As a regular feature of many web applications that need to work with Audio Files, the duration of an audio is a critical must known, specially on those apps that doesn't require all of the metadata properties of an Audio. In this article, we will explain you how to easily obtain the duration of an audio file using 2 differents method on the browser, programatically using the Embed Audio Tag or with the AudioContext API interface with JavaScript.

If you don't have any audio file at hand, you can download quickly some copyright free song from a website like Puma Studios here.

A. Using Audio Tag

The easiest way to obtain the duration of an audio file is through the embed Audio tag, used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element nested on the audio tag.

A.1 Reading from a local file

As first option, you may read the audio file locally and obtain the duration of the audio through this method:

// Create a non-dom allocated Audio element
var audio = document.createElement('audio');

// Add a change event listener to the file input
document.getElementById("fileinput").addEventListener('change', function(event){
    var target = event.currentTarget;
    var file = target.files[0];
    var reader = new FileReader();
  
    if (target.files && file) {
        var reader = new FileReader();

        reader.onload = function (e) {
            audio.src = e.target.result;
            audio.addEventListener('loadedmetadata', function(){
                // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
                var duration = audio.duration;
            
                // example 12.3234 seconds
                console.log("The duration of the song is of: " + duration + " seconds");
                // Alternatively, just display the integer value with
                // parseInt(duration)
                // 12 seconds
            },false);
        };

        reader.readAsDataURL(file);
    }
}, false); 

A.2 Reading from a web URL

Alternatively, if you want to obtain the duration of an audio file from a remote source (a server), it's quite easier and shorter than the others implementations:

// Create a non-dom allocated Audio element
var au = document.createElement('audio');

// Define the URL of the MP3 audio file
au.src = "https://mydomain.com/myaudio.mp3";

// Once the metadata has been loaded, display the duration in the console
au.addEventListener('loadedmetadata', function(){
    // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
    var duration = au.duration;

    // example 12.3234 seconds
    console.log("The duration of the song is of: " + duration + " seconds");
    // Alternatively, just display the integer value with
    // parseInt(duration)
    // 12 seconds
},false);

B. Using JS AudioContext

The first option to retrieve the duration of a song is through the AudioContext interface. This API represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode. An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.

We will show you how to obtain the duration using this interface with 2 examples, reading the audio file from a local source or a web URL:

B.1 Reading from a local file

In order to know the duration of an audio file that the user selects in a file type input, we will need to have basically the fileinput in our markup, in this case our id will be fileinput:

<input type="file" id="fileinput"/>

Then, we will attach an event listener to the input, so when the user selects a file, a callback will be triggered. In this callback, we will obtain the first uploaded file and we'll store it into a variable. We will create an instance of the FileReader class of JavaScript. This class lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. Then, attach to the onload event of the FileReader a callback that will contain the important code to obtain the duration of the audio file.

Create an instance of the AudioContext API and run the decodeAudioData method that receives as first argument the the result object of the resultant event. This method receives as well a callback that provides the audio buffer object, from where you can obtain the duration of the audio:

// Add a change event listener to the file input
document.getElementById("fileinput").addEventListener('change', function(){

    // Obtain the uploaded file, you can change the logic if you are working with multiupload
    var file = this.files[0];
    
    // Create instance of FileReader
    var reader = new FileReader();

    // When the file has been succesfully read
    reader.onload = function (event) {

        // Create an instance of AudioContext
        var audioContext = new (window.AudioContext || window.webkitAudioContext)();

        // Asynchronously decode audio file data contained in an ArrayBuffer.
        audioContext.decodeAudioData(event.target.result, function(buffer) {
            // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
            var duration = buffer.duration;

            // example 12.3234 seconds
            console.log("The duration of the song is of: " + duration + " seconds");
            // Alternatively, just display the integer value with
            // parseInt(duration)
            // 12 seconds
        });
    };

    // In case that the file couldn't be read
    reader.onerror = function (event) {
        console.error("An error ocurred reading the file: ", event);
    };

    // Read file as an ArrayBuffer, important !
    reader.readAsArrayBuffer(file);
}, false);

B.2 Reading from a web URL

As alternative, if the Audio file is located in your server or a third party server, yoy may simply retrieve the file with an AJAX request and reading it as well setting the responseType as arraybuffer, so you can easily obtain this information as well:

// Request URL of the Audio File
var mp3file = "https://mydomain.com/myaudio.mp3";

// Create an instance of AudioContext
var audioContext = new (window.AudioContext || window.webkitAudioContext)();

// Open an Http Request
var request = new XMLHttpRequest();
request.open('GET', mp3file, true);
request.responseType = 'arraybuffer';
request.onload = function() {
    audioContext.decodeAudioData(request.response, function(buffer) {
        // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
        var duration = buffer.duration;

        // example 12.3234 seconds
        console.log("The duration of the song is of: " + duration + " seconds");
        // Alternatively, just display the integer value with
        // parseInt(duration)
        // 12 seconds
    });
};

// Start Request
request.send();

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors