Triggering an HTML5 audio track to play whenever it has loaded

KemanoThief picture KemanoThief · Jul 5, 2011 · Viewed 8k times · Source

I'm trying to play an HTML5 audio track a few seconds after the page has loaded using the .play() JavaScript function.

Sometimes, when the audio loads slowly, and .play() is triggered when the player looks like this: enter image description here

The audio does not play when it is buffered.

Sometimes, when the audio loads quickly and the player looks like this, .play() works fine.

enter image description here

What is the quickest way around this issue? (Using a listener? I holding out for a 'play when loaded' function).

Answer

Lightnin' Myers picture Lightnin' Myers · Jul 15, 2011

This should be working:

<script language="JavaScript" type="text/javascript">
    var myAudio = document.getElementById('audio1')
    myAudio.oncanplaythrough = function () {this.play();}
</script>

<audio id="audio1" controls preload="auto" />
<audio id="audio2" controls preload="auto" oncanplaythrough="this.play();" />