Setting the currentTime of an <audio> tag not working?

fishbaitfood picture fishbaitfood · Dec 24, 2011 · Viewed 18.4k times · Source

I have this audio tag playing in the background, and I'm able to store the progress in seconds to a cookie. But in no way I'm able to start the audio from that cookie. (for continuing on other pages)

$("p#sound audio").currentTime = $.cookie("audioTime");

<audio autoplay="autoplay" loop="loop" ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime); $.cookie('audioTime', Math.floor(this.currentTime));">
    <source src="audio/song.ogg" type="audio/ogg" />
    <source src="audio/song.mp3" type="audio/mp3" />
    Your browser does not support the audio tag.
</audio>
<span id="tracktime">0</span>

Does this have to do with the song being loaded again from start?

Thanks!

EDIT:

$("p#sound audio").get[0].currentTime

With .get[0], it doesn't work either.

Can someone please clear things up for me? Greatly appreciated!

Answer

Brian Hadaway picture Brian Hadaway · Mar 7, 2012

You need to wait until audio source loads before you set the current time.

$(function(){
    $('audio').bind('canplay', function(){
        $(this)[0].currentTime = $.cookie('audioTime');
    });
});