gisly gisly - 2 months ago 18
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="http://www.music.helsinki.fi/tmt/opetus/uusmedia/esim/a2002011001-e02.wav" controls
start="1000" end="2000">
</audio>
<script>

$('audio').bind('canplay', function(event) {
alert("fire!");
event.target.currentTime = 0.5;
});
</script>


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

Answer

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!");
    event.target.currentTime = 0.5;
});
Comments