【问题标题】:Playing audio file returns "Uncaught (in promise)" but works in console播放音频文件返回“未捕获(承诺)”但在控制台中工作
【发布时间】:2019-05-15 12:03:09
【问题描述】:

我正在尝试播放音频文件(我尝试了很多)。它们都是mp3。 我已经在 MAMP localhost 以及在浏览器中运行它测试了以下内容。

我使用以下 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);
    })
}

什么都不返回 ("")

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

testSound.play()

声音按预期播放。

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

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

编辑:

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

编辑 2:

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

【问题讨论】:

    标签: javascript html asynchronous audio html5-audio


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我没有得到这么详细的错误,只有我显示的那个。当我抓住它时,它什么也没显示,正如我上面详述的那样。我抓错了吗?尽管如此,非常感谢您的帮助,这似乎是问题所在。
    • 有没有什么方法可以在没有人工干预的情况下播放音频?
    • 是的。无需用户交互即可播放视频。 ``` document.getElementById('video').autoplay = true; document.getElementById('video').muted = true; document.getElementById('video').play(); ```
    • @liberborn 我尝试了您的建议,但这不适用于音频对象任何其他指导?
    猜你喜欢
    • 2019-07-10
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2015-11-21
    • 1970-01-01
    • 2019-07-21
    相关资源
    最近更新 更多