8

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.
}
Akhil Sundar
  • 1,267
  • 5
  • 18
  • 32
  • I am not sure why you are using `Math.floor` here. Without `Math.floor`, the value of `element.currentTime` _should_ contain as much precision as the browser can afford. Hence, `element.currentTime * 1000` should give you the current time in milliseconds. Am I misunderstanding something? – musically_ut Apr 13 '14 at 06:24
  • @musically_ut: Yeah, that could be more helpful. Its possible to use the precision values for showing the time value upto milliseconds. Great Thanks. – Akhil Sundar Apr 13 '14 at 07:39

1 Answers1

11

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.

Community
  • 1
  • 1
Arnaud Leyder
  • 6,674
  • 5
  • 31
  • 43