我正在使用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.
}
您可以使用:
<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>
您可以在此处阅读有关timeupdate事件精度的更多信息。它取决于浏览器的实现,因此请记住,从浏览器/设备到另一个设备,您将获得不同的结果。
您应该使用addEventListener方法而不是ontimeupdate属性-它更易于维护。
同样,如果需要浏览器覆盖,最好同时使用ogg和mp3音频文件作为源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句