Javascript 如何检查是否加载了 HTML5 音频元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8059434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you check if a HTML5 audio element is loaded?
提问by auragar
I am wanting to know how to check if a HTML5 audio element is loaded.
我想知道如何检查是否加载了 HTML5 音频元素。
回答by robertc
To find out when the audio is ready to start playing, add listeners for the oncanplay
or oncanplaythrough
events. To find out when the audio has loaded at all, listen to the onloadeddata
event:
要了解音频何时准备好开始播放,请为oncanplay
或oncanplaythrough
事件添加侦听器。要了解音频何时完全加载,请收听onloadeddata
事件:
<audio oncanplay="myOnCanPlayFunction()"
oncanplaythrough="myOnCanPlayThroughFunction()"
onloadeddata="myOnLoadedData()"
src="myaudio.ogg"
controls>
<a href="myaudio.ogg">Download</a>
</audio>
<script>
function myOnCanPlayFunction() { console.log('Can play'); }
function myOnCanPlayThroughFunction() { console.log('Can play through'); }
function myOnLoadedData() { console.log('Loaded data'); }
</script>
回答by lk145
Check out robertc's answer for how to use event listeners. You can also directly check an audio element's ready state:
查看 robertc 的答案以了解如何使用事件侦听器。您还可以直接检查音频元素的就绪状态:
var myAudio = $('audio')[0];
var readyState = myAudio.readyState;
readyState
will be a number. From Mozilla's docs:
readyState
将是一个数字。来自Mozilla 的文档:
- 0 - No information is available about the media resource.
- 1 - Enough of the media resource has been retrieved that the metadata attributes are initialized. Seeking will no longer raise an exception.
- 2 - Data is available for the current playback position, but not enough to actually play more than one frame.
- 3 - Data for the current playback position as well as for at least a little bit of time into the future is available (in other words, at least two frames of video, for example).
- 4 - Enough data is available—and the download rate is high enough—that the media can be played through to the end without interruption.
- 0 - 没有关于媒体资源的可用信息。
- 1 - 已检索到足够的媒体资源以初始化元数据属性。寻求将不再引发异常。
- 2 - 数据可用于当前播放位置,但不足以实际播放多于一帧。
- 3 - 当前播放位置以及未来至少一小段时间的数据可用(换句话说,例如至少两帧视频)。
- 4 - 有足够的数据可用 - 并且下载速率足够高 - 媒体可以不间断地播放到最后。