Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
}
like image 285
Akhil Sundar Avatar asked Apr 13 '14 05:04

Akhil Sundar


People also ask

Can you style HTML5 audio tags?

HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls. You can also add CSS classes to each one of the elements and style them accordingly.

What are the 2 tags for embedding audio in HTML?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.

What is the correct HTML5 element for playing audio files?

The HTML <audio> element is used to play an audio file on a web page.


1 Answers

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.

like image 84
Arnaud Leyder Avatar answered Oct 21 '22 10:10

Arnaud Leyder