[英]How do I catch an audio DOMException caused by a file that cannot play?
If I try and play a non-existing audio file (eg the file hasn't downloaded yet) like this:如果我尝试播放一个不存在的音频文件(例如,该文件尚未下载),如下所示:
audio_object = new Audio("Non_Existing_Audio_File.mp3");
audio_object.play();
I get:我得到:
Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.
That's fine, but how can I catch that error?很好,但是我怎样才能捕捉到这个错误呢? If I do a try/catch, this is what happens:
如果我执行 try/catch,就会发生以下情况:
function playAudioWithTryCatch() {
try {
audio_object.play();
//Result: Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.
} catch (error) {
// We never get here:
console.error("Audio play failed",error);
}
}
So with try/catch I never get as far as the catch block, only the same unhandled error message when the play method is called.因此,对于 try/catch,我永远不会到达 catch 块,只有在调用 play 方法时出现相同的未处理错误消息。
If I try using a Promise I get:如果我尝试使用 Promise,我会得到:
function playAudioWithPromise(){
let myPromise = new Promise(function(resolve, reject) {
if (E2.play()) {
resolve("OK");
} else {
reject("Error");
}
});
myPromise.then(
result => console.log(result),
error => console.log(error)
);
//Result: Uncaught (in promise) DOMException: The media resource indicated by the src attribute or assigned media provider object was not suitable.
//And "OK" (console log)
}
Again, the error is not caught, similar to above.同样,错误没有被捕获,与上面类似。
Can anyone tell me how to catch/handle this error before it gets output to the console?谁能告诉我如何在将 output 发送到控制台之前捕获/处理此错误?
I know I can use the media readyState
property but that doesn't help in this case since I'm trying to work around a Safari issue whereby the readyState doesn't show ready until a user has initiated each and every audio file play method, which is impractical so I can't use that here.我知道我可以使用媒体
readyState
属性,但这在这种情况下没有帮助,因为我正在尝试解决 Safari 问题,即 readyState 在用户启动每个音频文件播放方法之前不会显示就绪,这是不切实际的,所以我不能在这里使用它。
Any help appreciated!任何帮助表示赞赏!
audio_object.play()
itself returns a promise. Catch the error with a .catch()
like a normal promise. I found that out by testing the following code and inspecting the variables in my browser: audio_object.play()
本身返回 promise。使用.catch()
捕获错误,就像正常的 promise 一样。我通过测试以下代码并检查浏览器中的变量发现了这一点:
function start() {
audio_object = new Audio("Non_Existing_Audio_File.mp3");
window.playResult = audio_object.play();
playResult.catch(e => {
window.playResultError = e;
})
}
start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.