当 HTML5 <audio> 元素无法播放时如何使用 jQuery 或 JavaScript 进行检测
How to detect with jQuery or JavaScript when HTML5 <audio> element cannot play
我在一个包含来自远程站点的 mp3 的页面上有许多音频元素,有时加载 mp3 的请求会导致 301 Moved Permanently
响应。
发生这种情况时,播放器变成灰色,但我无法检测到任何错误。我尝试做这样的事情,但处理程序永远不会 运行:
$('audio').on('error', function(){
// Code to handle the error
});
我注意到音频元素的 networkState
is 3
and it's readyState
is 0
when I check these in the console after the page has finished loading, but I can't find an event 处理在达到这些状态后发生。
当 mp3 无法加载并且音频元素变得无法播放时,我该如何做一些事情(运行 函数、显示模式等)?
这是一个简单的解决方案!
window.onload=function(){
let audioElem=document.querySelectorAll("audio")[0];
canBePlayed(audioElem);
}
function canBePlayed(audio){
if(audio.readyState!=0){
alert("This audio can be played!");
}else{
alert("This audio can not be played!");
}
}
<audio src="./audio.ogg" controls>
Your Browser doesn't support this type of audios
</audio>
我在一个包含来自远程站点的 mp3 的页面上有许多音频元素,有时加载 mp3 的请求会导致 301 Moved Permanently
响应。
发生这种情况时,播放器变成灰色,但我无法检测到任何错误。我尝试做这样的事情,但处理程序永远不会 运行:
$('audio').on('error', function(){
// Code to handle the error
});
我注意到音频元素的 networkState
is 3
and it's readyState
is 0
when I check these in the console after the page has finished loading, but I can't find an event 处理在达到这些状态后发生。
当 mp3 无法加载并且音频元素变得无法播放时,我该如何做一些事情(运行 函数、显示模式等)?
这是一个简单的解决方案!
window.onload=function(){
let audioElem=document.querySelectorAll("audio")[0];
canBePlayed(audioElem);
}
function canBePlayed(audio){
if(audio.readyState!=0){
alert("This audio can be played!");
}else{
alert("This audio can not be played!");
}
}
<audio src="./audio.ogg" controls>
Your Browser doesn't support this type of audios
</audio>