[英]Timing issues with playback of the HTML5 Audio API
I'm using the following code to try to play a sound clip with the HTML5 Audio API: 我正在使用以下代码尝试使用HTML5音频API播放声音片段:
HTMLAudioElement.prototype.playClip = function(startTime, stopTime) {
this.stopTime = stopTime;
this.currentTime = startTime;
this.play();
$(this).bind('timeupdate', function(){
if (this.ended || this.currentTime >= stopTime) {
this.pause();
$(this).unbind('timeupdate');
}
});
}
I utilize this new playClip
method as follows. 我利用这种新的
playClip
方法,如下所示。 First I have a link with some data
attributes: 首先,我有一个带有一些
data
属性的链接:
<a href=# data-stop=1.051 data-start=0.000>And then I was thinking,</a>
And finally this bit of jQuery which runs on $(document).ready
to hook up a click on the link with the playback: $('a').click(function(ev){ 最后是运行在
$(document).ready
上的jQuery的这一部分,准备在播放时链接到该链接:$('a')。click(function(ev){
$('a').click(function(ev){
var start = $(this).data('start'),
stop = $(this).data('stop'),
audio = $('audio').get(0),
$audio = $(audio);
ev.preventDefault();
audio.playClip(start,stop);
})
This approach seems to work, but there's a frustrating bug: sometimes, the playback of a given clip plays beyond the correct data-stop
time. 这种方法似乎可行,但是有一个令人沮丧的错误:有时,给定剪辑的播放超出了正确的
data-stop
时间。
I suspect it could have something to do with the timing of the timeupdate
event, but I'm no JS guru and I don't know how to begin debugging the problem. 我怀疑这可能与
timeupdate
事件的时间有关,但我不是JS专家,而且我不知道如何开始调试问题。 Here are a few clues I've gathered: 这是我收集的一些线索:
Is the problem here the inherent accuracy of the Audio API? 这里的问题是音频API的固有准确性吗? My app needs milliseconds.
我的应用需要毫秒。
Is there a problem with the way I'm using jQuery to bind and unbind the timeupdate
event? 我使用jQuery绑定和取消绑定
timeupdate
事件的方式是否存在问题? I tried using the jQuery-less approach with addEventListener
but I couldn't get it to work. 我尝试将无jQuery的方法与
addEventListener
但无法正常工作。
Thanks in advance, I would really love to know what's going wrong. 在此先感谢,我真的很想知道出什么问题了。
The timeupdate
event fires only 3-4 times a second or so, nowhere near millisecond accuracy. timeupdate
事件timeupdate
仅触发3-4次,准确度不及毫秒。 Then again it's better than setTimeout
/ setInterval
which fires only once per second if the tab is not active in google chrome (a common use case for audio file listening). 再说一次,它比
setTimeout
/ setInterval
更好,后者在google chrome中不激活该选项卡时(每秒侦听音频文件的一种常用情况),每秒仅触发一次。
If however in your app you can ensure that the tab is active while listening, then setTimeout
or setInterval
is better as it can fire as often as 100 times per second. 但是,如果在您的应用程序中可以确保在收听时该选项卡处于活动状态,则
setTimeout
或setInterval
更好,因为它每秒可以触发setInterval
100次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.