javascript 播放音频文件返回“未捕获(承诺)”但在控制台中工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53775957/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:17:43  来源:igfitidea点击:

Playing audio file returns "Uncaught (in promise)" but works in console

javascripthtmlasynchronousaudiohtml5-audio

提问by PolymorphismPrince

I'm trying to play audio files (I've tried many). All of them are mp3s. I've tested the following on both MAMP localhost and also by just running it in the browser.

我正在尝试播放音频文件(我尝试了很多)。它们都是mp3。我已经在 MAMP 本地主机上测试了以下内容,也只是在浏览器中运行它。

I use the following javascript:

我使用以下 javascript:

var testSound = new Audio();
testSound.src = "a.mp3"
setTimeout(testSound.play.bind(testSound),100)

This returns the error:

这将返回错误:

Uncaught (in promise)

Trying to catch it:

试图抓住它:

var testSound = new Audio();
testSound.src = "a.mp3"
setTimeout(playSound,100)
function playSound () {
    testSound.play().then(response => {

    }).catch(e => {
        console.log(e);
    })
}

returns nothing ("")

不返回任何内容 ( "")

But if I now turn to the console and simply type:

但是如果我现在转向控制台并简单地输入:

testSound.play()

The sound plays as it's supposed to.

声音按预期播放。

Even if I comment the third line of the first code snippet like:

即使我评论第一个代码片段的第三行,如:

//setTimeout(testSound.play.bind(testSound),100)

Edit:

编辑:

Even if people don't know what the solution is I'd still be interested to know if they can reproduce the error.

即使人们不知道解决方案是什么,我仍然有兴趣知道他们是否可以重现错误。

Edit 2:

编辑2:

By the way, the problem doesn't persist in Firefox or Safari.

顺便说一下,该问题在 Firefox 或 Safari 中不会持续存在。

回答by duskwuff -inactive-

If you read the full error message associated with the exception, you'll get a better explanation:

如果您阅读与异常相关的完整错误消息,您将得到更好的解释:

? Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD

? Uncaught (in promise) DOMException: play() 失败,因为用户没有先与文档交互。https://goo.gl/xX8pDD

Google's article "Autoplay Policy Changes" (linked in the message above) explains the situation in detail.

Google 的文章“ Autoplay Policy Changes”(链接在上面的消息中)详细解释了这种情况。

The short version is: if you want to play audio or video, you need to wait to do it until the user has clicked something on the page.

简短的版本是:如果要播放音频或视频,则需要等到用户单击页面上的某些内容后才能播放。