A quick javascript hack to fake adjusting HTML5 audio elements' timeupdate event frequency

I was trying to make a bunch of elements change position as an audio file played, using a snippet something like:

$(audiohtml).bind("timeupdate", onAudioUpdate);
$(audiohtml).bind("play", onAudioUpdate);
$(audiohtml).bind("pause", onAudioUpdate);

function onAudioUpdate() {
	// Move the elements here
}

But the trouble was that the audio element's timeupdate event only fires once every 200ms or so on my browser (this is set by the HTML5 audio specification and isn't modifiable as far as I know).

200ms was slow enough that the animation of the elements looked jerky (5 fps).

Instead, I used a 10Hz setInterval clock to trigger the movement functions, and used the audio's play and pause events to create and destroy the clock:

var audio_clock;

$(audiohtml).bind("timeupdate", onAudioUpdate);
$(audiohtml).bind("play", function(){
		audio_clock = setInterval(function(){
				onAudioUpdate();
			}, 100);
	});
$(audiohtml).bind("pause", function(){
		clearInterval(audio_clock);
	});

function onAudioUpdate() {
	// Move the elements here
}

In the play even binding, I use an anonymous function so that I could assign to the audio_clock variable with something a bit complicated. Within that function I use another anonymous function because my onAudioUpdate function is otherwise outside the scope of the setInterval, and so would otherwise appear to be onAudioUpdate undefined.

By tying the start/stop of the setInterval clock to the audio elements' play and pause events, it has similar functionality to the timeupdate event. Keeping the timeupdate binding in there means that if the playhead updates through some method other than playing (such as seeking), my onAudioUpdate function gets called anyway.

2 comments

  1. He Shiming says:

    Huh, some smart trick, and elegant. Thanks!

    1. Cai says:

      No probs, glad it helped you out.

Leave a comment

Your email address will not be published. Required fields are marked *