gpt4 book ai didi

javascript - HTML5 : How to get currentTime and duration of Audio Tag in milliseconds

转载 作者:太空狗 更新时间:2023-10-29 13:45:38 26 4
gpt4 key购买 nike

我在我的模板中使用 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>

您可以在此处阅读有关时间更新精度的更多信息 event .它取决于浏览器的实现,因此请记住,从浏览器/设备到另一个浏览器/设备,您会得到不同的结果。

您应该使用 addEventListener 方法而不是 ontimeupdate 属性 - 它更易于维护。

此外,如果您需要浏览器覆盖,最好同时使用 ogg 和 mp3 音频文件作为源。

关于javascript - HTML5 : How to get currentTime and duration of Audio Tag in milliseconds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23039635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com