开发者

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:

Triggering an HTML5 audio track to play whenever it has loaded

The audio does not play when it is buffered.

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

Triggering an HTML5 audio track to play whenever it has loaded

What is the quickest way around this issue?开发者_如何学运维 (Using a listener? I holding out for a 'play when loaded' function).


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


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.


You can set:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜