Timing issues with playback of the HTML5 Audio API
Posted
by
pat
on Stack Overflow
See other posts from Stack Overflow
or by pat
Published on 2011-11-22T01:45:09Z
Indexed on
2011/11/22
1:51 UTC
Read the original article
Hit count: 186
JavaScript
|html5-audio
I'm using the following code to try to play a sound clip with the HTML5 Audio 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. First I have a link with some data
attributes:
<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){
$('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.
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. Here are a few clues I've gathered:
- The same behavior appears to come up in both FF and Chrome.
- The playback of a given clip actually seems to vary a bit -- if I play the same clip a couple times in a row, it may over-play a different amount of time on each playing.
Is the problem here the inherent accuracy of the Audio API? My app needs milliseconds.
Is there a problem with the way I'm using jQuery to bind and unbind the timeupdate
event? I tried using the jQuery-less approach with addEventListener
but I couldn't get it to work.
Thanks in advance, I would really love to know what's going wrong.
© Stack Overflow or respective owner