html5 display audio currentTime

Here's an example:

<audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
       ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
    <p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>

This should work in Firefox and Chrome, for other browsers you'll probably need to add alternative encodings.


robertc's version will work fine except for the fact that it does not turn the number of seconds you get from math.floor() into proper time values.

Here is my function called when ontimeupdate is called:

<audio id='audioTrack' ontimeupdate='updateTrackTime(this);'>
  Audio tag not supported in this browser</audio>
<script>
function updateTrackTime(track){
  var currTimeDiv = document.getElementById('currentTime');
  var durationDiv = document.getElementById('duration');

  var currTime = Math.floor(track.currentTime).toString(); 
  var duration = Math.floor(track.duration).toString();

  currTimeDiv.innerHTML = formatSecondsAsTime(currTime);

  if (isNaN(duration)){
    durationDiv.innerHTML = '00:00';
  } 
  else{
    durationDiv.innerHTML = formatSecondsAsTime(duration);
  }
}
</script>

I modified formatSecondsAsTime() from something I found here:

function formatSecondsAsTime(secs, format) {
  var hr  = Math.floor(secs / 3600);
  var min = Math.floor((secs - (hr * 3600))/60);
  var sec = Math.floor(secs - (hr * 3600) -  (min * 60));

  if (min < 10){ 
    min = "0" + min; 
  }
  if (sec < 10){ 
    sec  = "0" + sec;
  }

  return min + ':' + sec;
}

here is simple usage. keep in mind html5 elements are still in the works so anything can change:

    audio = document.getElementsByTagName("audio")[0];

    //functions
    audio.load();
    audio.play();
    audio.pause();

    //properties
    audio.currentSrc  
    audio.currentTime  
    audio.duration

here is the reference HTML5 Audio

to get the currentTime while audio is playing you must attach the timeupdate event and update your current time within the callback function.

simple tutorial audio/video html5 on dev.opera