Akhil Sundar
Akhil Sundar

Reputation: 1317

HTML5: How to get currentTime and duration of Audio Tag in milliseconds

I am using HTML5 audio tag for playing sound files in my template. For some purpose I need to track the currentTime and duration which shows upto milliseconds. Now I am able to get the values in seconds only. Is there any possible methods? Below is my code:

HTML
<audio controls id="track" src="<path-to-soundtrack>"
   ontimeupdate="TrackAudio(this)">
<p>Your browser does not support the audio element</p>
</audio>


JAVASCRIPT
function TrackAudio(element){
var curTime = Math.floor(element.currentTime);
console.log(curTime)   //Value in seconds.
}

Upvotes: 8

Views: 21979

Answers (1)

Arnaud Leyder
Arnaud Leyder

Reputation: 7002

You can use:

<audio id="track" controls>
  <source src="your.mp3" type="audio/mpeg">
  <source src="your.ogg" type="audio/ogg">
</audio> 
<script type="text/javascript">
var audio = document.getElementById('track');
audio.addEventListener('timeupdate',function(){
    var currentTimeMs = audio.currentTime*1000;
    console.log(currentTimeMs);
},false);
</script>

You can read here for more information on the precision of the timeupdate event. It is dependent on the browser implementation so keep in mind you will get different results from a browser/device to another.

You should use addEventListener method rather than the ontimeupdate property - it is more maintainable.

Also if you need browser coverage it is good to use both ogg and mp3 audio files as sources.

Upvotes: 11

Related Questions