2

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.

James Juanjie
  • 219
  • 3
  • 18
  • Possible duplicate of [How can I pad a value with leading zeros?](https://stackoverflow.com/questions/1267283/how-can-i-pad-a-value-with-leading-zeros) – Heretic Monkey Nov 26 '18 at 20:11

2 Answers2

5

You have this code to convert the time to the 00:00 format, but you only use it for the currentTime. Turn it into a function and use it for both.

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

    return mins + ':' + secs;
}

$('.Audio_durationTime').text(convertTime(audio.duration));
$('.Audio_passedTime').text(convertTime(audio.currentTime));
user1178830
  • 436
  • 3
  • 11
0

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/

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    The OP has code that does that, doesn't he? `if (mins < 10) { mins = '0' + String(min); }`? Also, your code would add a 0 at the end, so you'd end up with `90` instead of `09`. – Heretic Monkey Nov 26 '18 at 20:08
  • @HereticMonkey, i actually do but for some strange reason when I was using it for the duration, it wasn't working! I must have been doing something wrong. – James Juanjie Nov 26 '18 at 20:10
  • 1
    Yes he does, but it is missing for the duration time. – The fourth bird Nov 26 '18 at 20:10