Format the currentTime property in HTML5 audio and video

...for use in counters and progress bars

Javascript, Date Formatting, Time

The HTML5 audio element returns the current time of a song or sound file in a sixty second based format starting from zero, such that one second is reported as 1, 1 minute as 60, one minute and one second as 61, etc. However, most video and audio players we are familiar with will represent that data as :01, 1:01, etc. So how to make that conversion in javascript? First, of course, you need to declare your audio element and a sound file:

var audio = new Audio("song.mp3");

Then add an event listener to that audio element to track the currentTime property:

audio.addEventListener("timeupdate", function() { });

and within that function, create variables to hold the minutes and seconds.

add an event listener to your audio element, and within that, create variables to hold both the seconds and minutes :


audio.addEventListener("timeupdate", function() {);
      var s = parseInt(audio.currentTime % 60);
      var m = parseInt((audio.currentTime / 60) % 60);
}, false);

Of course, we'll need somewhere to display this. I've created an empty div with the class "duration", and passed it the minutes and seconds, separated by a colon.



audio.addEventListener("timeupdate", function() {
    var duration = document.getElementById('duration');
    var s = parseInt(audio.currentTime % 60);
    var m = parseInt((audio.currentTime / 60) % 60);
     duration.innerHTML = m + ':' + s ;
}, false);