3

I am trying to convert seconds to MM:SS and for some reason it is not showing correctly.

jQuery('#player-recorded-call').get(0).currentTime; is to get <audio> current time position.

For example

audioCurrentTime was set to 326.459368 which SHOULD be 05:26 (MM:SS) but for some reason it has been calculated to 05:84 (var dur)

    var audioCurrentTime = jQuery('#player-recorded-call').get(0).currentTime;

    var minutes = "0" + Math.floor(audioCurrentTime / 60);
    var seconds = "0" + (audioCurrentTime - minutes * 60);
    var dur = minutes.substr(-2) + ":" + seconds.substr(-2);

    $(".criteria-duration").html(dur);

I got this math example from https://stackoverflow.com/a/26206645/791022

Community
  • 1
  • 1
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

2 Answers2

4

Your are missing the Math.floor call for seconds and get the last 2 digit of it, that is 84.

Updated code shall be :

var audioCurrentTime = jQuery('#player-recorded-call').get(0).currentTime;

var minutes = "0" + Math.floor(audioCurrentTime / 60);
var seconds = "0" +  Math.floor(audioCurrentTime - minutes * 60);
var dur = minutes.substr(-2) + ":" + seconds.substr(-2);

$(".criteria-duration").html(dur);
aorfevre
  • 5,034
  • 3
  • 21
  • 51
3

Since audioCurrentTime isn’t a whole number, (audioCurrentTime - minutes * 60) won’t be either, and you’ll end up with a string like "0326.4593684". Taking the last two characters of that, you get 05:84.

You can truncate audioCurrentTime first:

var seconds = "0" + (Math.floor(audioCurrentTime) - minutes * 60);

The % (modulus) operator is also nice:

var seconds = "0" + Math.floor(audioCurrentTime % 60);
Ry-
  • 218,210
  • 55
  • 464
  • 476