javascript HTML5:如何以毫秒为单位获取音频标签的当前时间和持续时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23039635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5: How to get currentTime and duration of Audio Tag in milliseconds
提问by Akhil Sundar
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:
我正在使用 HTML5 音频标签在我的模板中播放声音文件。出于某种目的,我需要跟踪显示最多毫秒的 currentTime 和持续时间。现在我只能在几秒钟内获得这些值。有什么可行的方法吗?下面是我的代码:
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.
}
回答by Arnaud Leyder
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.
您可以在此处阅读有关 timeupdate事件精度的更多信息。它取决于浏览器的实现,因此请记住,您将在浏览器/设备之间获得不同的结果。
You should use addEventListener method rather than the ontimeupdate property - it is more maintainable.
您应该使用 addEventListener 方法而不是 ontimeupdate 属性 - 它更易于维护。
Also if you need browser coverage it is good to use both ogg and mp3 audio files as sources.
此外,如果您需要浏览器覆盖,最好同时使用 ogg 和 mp3 音频文件作为源。