Search code examples
javascripthtmlaudiohtml5-audiojavascript-audio-api

Parsing and showing HTML audio current time with javascript


I'm working on a plain JavaScript + HTML audio player and at this time I want to build a interface that show the current time of the audio in the form "MM:SS". For what I could search the HTML Audio/Video DOM Reference has only one native function - audio|video.currentTime - that return the current audio time in seconds with a large decimal precision.

In order to do this I code:

HTML

<audio id='audio' src="http://www.stephaniequinn.com/Music/Canon.mp3" controls></audio>
<div id="timer">00:00</div>

JavaScript

var audio = document.getElementById('audio'),
      timer = document.getElementById('timer');

var update = setInterval(function() {

  timer.innerHTML = audio.currentTime;
}, 10);

I tried a bunch of thing but I could not format the output the way I wanted. Hope some of you guys can bring some light on this.

Codepen sample


Solution

  • Working edited CodePen

    Just needed a little math! JS below:

    var update = setInterval(function() {
          var mins = Math.floor(audio.currentTime / 60);
          var secs = Math.floor(audio.currentTime % 60);
          if (secs < 10) {
            secs = '0' + String(secs);
          }
          timer.innerHTML = mins + ':' + secs;
        }, 10);