Search code examples
javascripthtmlaudio

Converting <audio> currentTime to accurate time display


I'm trying to get an audio's current time to display as hours:minutes:seconds (00:00:00) rather than just in 'seconds' or 'minutes and seconds'. The current code is what I have...

<audio id="audio" ontimeupdate="document.getElementById('tracktime').innerHTML = '0' + Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration); " src="music.mp3"></audio>

This displays the seconds as 0 / 0 inside of the following...

<span id="tracktime">0 / 0</span>

I have searched for hours and all of the solutions I have found are simply doing nothing.

I even found the following code to assist but am not sure how to implement this into the 'ontimeupdate' action in the audio tag.

var minutes = '0' + Math.floor(currentTime / 60); var seconds = '0' + (currentTime - minutes * 60); var cur = minutes.substr(-2) + ':' + seconds.substr(-2);

If possible, I would like it to display as two seperate items. Like so...

<div id="currentTime"></div>
<div id="duration"></div>

Solution

  • Here is a sample how you can do

    window.addEventListener('load', function() {
      var cur = document.querySelector('#cur'),
          dur = document.querySelector('#dur')
          vid = document.querySelector('#aud')
    })
        
    aud.addEventListener('timeupdate', function(e) {
      cur.textContent = "Current: " + sToTime(e.target.currentTime);
      dur.textContent = "Duration: " + sToTime(e.target.duration);
    })
    
    function sToTime(t) {
      return padZero(parseInt((t / (60 * 60)) % 24)) + ":" +
             padZero(parseInt((t / (60)) % 60)) + ":" + 
             padZero(parseInt((t) % 60));
    }
    function padZero(v) {
      return (v < 10) ? "0" + v : v;
    }
    <audio id="aud" controls>
      <source src="http://techslides.com/demos/samples/sample.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
    </audio>
    
    <p id="cur"></p>
    <p id="dur"></p>