【问题标题】:HTML5: How to get currentTime and duration of Audio Tag in millisecondsHTML5:如何以毫秒为单位获取音频标签的当前时间和持续时间
【发布时间】:2014-05-27 04:55:46
【问题描述】:

我正在使用 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.
}

【问题讨论】:

  • 我不知道你为什么在这里使用Math.floor。如果没有Math.floorelement.currentTime 的值应该包含浏览器所能承受的尽可能多的精度。因此,element.currentTime * 1000 应该以毫秒为单位为您提供当前时间。我是不是误会了什么?
  • @musically_ut:是的,这可能更有帮助。可以使用精度值来显示高达毫秒的时间值。非常感谢。

标签: javascript jquery html audio html5-audio


【解决方案1】:

你可以使用:

<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 event 精度的更多信息。它取决于浏览器的实现,因此请记住,您会从一个浏览器/设备到另一个浏览器/设备获得不同的结果。

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

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

【讨论】:

  • 这个答案没有解释你如何获得文件的总时间。
猜你喜欢
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2017-02-20
  • 2013-10-13
  • 1970-01-01
相关资源
最近更新 更多