播放音频文件返回“未捕获(在承诺中)".但可以在控制台中使用 [英] Playing audio file returns "Uncaught (in promise)" but works in console

查看:164
本文介绍了播放音频文件返回“未捕获(在承诺中)".但可以在控制台中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我使用以下javascript:

I use the following javascript:

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

这将返回错误:

Uncaught (in promise)

试图抓住它:

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

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

不返回任何内容("")

但是,如果我现在转到控制台,只需键入:

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

testSound.play()

声音按预期播放.

即使我将第一个代码段的第三行注释为:

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

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

即使人们不知道解决方案是什么,我仍然很想知道他们是否可以重现错误.

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

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

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

推荐答案

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

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

❌未捕获(承诺)的DOMException:play()失败,因为用户没有首先与文档进行交互. https://goo.gl/xX8pDD

Google的文章"自动播放政策更改"(上面的消息中链接)详细说明了这种情况.

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

简短的版本是:如果要播放音频或视频,则需要等待直到用户单击页面上的某些内容为止.

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.

这篇关于播放音频文件返回“未捕获(在承诺中)".但可以在控制台中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆