user18015
user18015

Reputation:

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:

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:

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.

Upvotes: 1

Views: 1749

Answers (1)

Esailija
Esailija

Reputation: 140220

The timeupdate event fires only 3-4 times a second or so, nowhere near millisecond accuracy. 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).

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.

Upvotes: 1

Related Questions