javascriptjqueryhtmlhtml5-audio

html5 get audio duration in 00:00 format?


I'm trying to get the HTML5 audio tag's duration in 00:00 format but I don't understand why my code gets the duration in this format: 0:00. So, there's 1 digit missing!

This is my current code:

$(audio).bind('timeupdate', function(){


  var minutes = parseInt(audio.duration / 60, 10);
  var seconds = parseInt(audio.duration % 60);


  $('.Audio_durationTime').text(minutes + ':' + seconds);



    /////Passed time////
    var mins = Math.floor(audio.currentTime / 60);
    if (mins < 10) {
      mins = '0' + String(mins);
    }
    var secs = Math.floor(audio.currentTime % 60);
    if (secs < 10) {
      secs = '0' + String(secs);
    }

    $('.Audio_passedTime').text(mins + ':' + secs);

});

And a working fiddle:

http://jsfiddle.net/8cpwv2mf/6/

Could someone please advice on this issue?

Thanks in advance.


Solution

  • You could add a zero if the minutes is lower than 10 for the duration time:

    if (minutes < 10) {
        minutes += "0";
    }
    $('.Audio_durationTime').text(minutes + ':' + seconds);
    

    Updated fiddle:

    http://jsfiddle.net/8cpwv2mf/7/