KemanoThief
KemanoThief

Reputation: 617

Triggering an HTML5 audio track to play whenever it has loaded

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).

Upvotes: 5

Views: 9206

Answers (3)

KemanoThief
KemanoThief

Reputation: 617

If the load is successful, whether using the src attribute or using source elements, then as data is being downloaded, progress events are fired. When enough data has been loaded to determine the video's dimensions and duration, a loadedmetadata event is fired. When enough data has been loaded to render a frame, the loadeddata event is fired. When enugh data has been loaded to be able to play a little bit of the video, a canplay event is fired. When the browser determines that it can play through the whole video without stopping for downloading more data, a canplaythrough event is fired; this is also when the video starts playing if it has a autoplay attribute.

Note: Opera 10.50 doesn't try to determine when it has enough data to be able to play through, but instead just fires canplay and canplaythrough at the same time. This will probably be fixed in a future release.

If the browser decides to stop downloading data in order to save bandwidth, then it will fire a suspend event. If the server stops giving data (without closing the connection) for some reason, then after three seconds the browser fires a stalled event. If the browser is playing faster than the server is serving data, or when seeking causes the browser to wait for downloading data, a waiting event is fired.

Note: Opera 10.50 doesn't suspend downloads yet, and doesn't fire the stalled event.

If you want to have your play button disabled until the video is able to play, you can enable it on the canplay event:

<input type="button" value="Play" id="playpause" onclick="playOrPause()" disabled>
video.oncanplay = function(e) {
  playpause.disabled = false;
}

Source.

Upvotes: 1

Ajay Menon
Ajay Menon

Reputation: 46

You can set:

<script>
var myAudio = document.getElementById('audio1');
myAudio.setAttribute('autoplay', 'autoplay');</script>

Upvotes: 0

Lightnin&#39; Myers
Lightnin&#39; Myers

Reputation: 64

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();" />

Upvotes: 4

Related Questions