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.
}
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.
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.
The HTML <audio> element is used to play an audio file on a web page.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With