gisly gisly - 8 months ago 58
Javascript Question

html5 audio: changing currentTime fires multiple canplay events

I need to change the offset time for an HTML5 audio element. I've written a function which handles the canplay event and changes the currentTime attribute.

However, it seems that changing the currentTime attribute fires the event and so it goes on in a loop. When I comment out the currentTime changing, it works normally (i. e. the event only fires once).

What is the proper way to do it? This behaviour occurs in (at least) Firefox and Chrome. As a result, the music does not play normally

<audio id="current" src="" controls
start="1000" end="2000">

$('audio').bind('canplay', function(event) {
alert("fire!"); = 0.5;

can check it on jsfiddle, too

Actually, it seems to work with the loadedmetadata event but everyone suggests canplay is better and compatible with more browsers


you can use .one instead of .bind in order to listen to it only on the first time

$('audio').one('canplay', function(event) {
    console.log("fire!"); = 0.5;