Get the Duration of an Audio or Video File in Javascript

It is quite easy to get the playback length (in seconds) of an audio or video file. The file may be in whatever format that the browser supports – mp3, mp4, ogg, wav, etc.

When Using the HTML5 Elements

When using the HTML5 <audio> or <video> elements, you can simply check the duration property in Javascript.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

var audio_duration = document.querySelector('audio').duration; // 10.026666641235352
// or
var video_duration = document.querySelector('video').duration;

Web Audio API

When working with the Web Audio API, you might load the Audio file in several ways. The most common way is using AJAX.

var ctx = new webkitAudioContext();

function loadMusic(url) {
  var req = new XMLHttpRequest();
  req.open('GET', url, true);
  req.responseType = 'arraybuffer';

  req.onload = function() {

    ctx.decodeAudioData(req.response, function(buffer) {
      console.log(buffer);
      console.log(buffer.duration); // 116
    })
  };

  req.send();
}

We loaded the audio file using XHR2 that supports the arraybuffer response type. Some other ways might include using the file input field or the FileSystem API to fetch the file from and then read that using FileReader.readAsArrayBuffer().

So, when the Audio Data in the ArrayBuffer (in the XHR response) is decoded by ctx.decodeAudioData (async and non-blocking), the callback we passed to it gets called. This callback receives, an AudioBuffer object that contains the duration property which holds the duration of the PCM Audio Data in seconds. This approach seems to work fine on a video file too!

Note: In both the methods discussed above, the duration value is a float representing the time in seconds.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *