正在播放音频文件 returns "Uncaught (in promise)" 但在控制台中有效
Playing audio file returns "Uncaught (in promise)" but works in console
我正在尝试播放音频文件(我试过很多)。都是mp3。
我已经在 MAMP localhost 上以及在浏览器中 运行 测试了以下内容。
我使用以下 javascript:
var testSound = new Audio();
testSound.src = "a.mp3"
setTimeout(testSound.play.bind(testSound),100)
这个returns错误:
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);
})
}
returns 没有 (""
)
但如果我现在转到控制台并简单地键入:
testSound.play()
声音正常播放。
即使我将第一个代码片段的第三行注释为:
//setTimeout(testSound.play.bind(testSound),100)
编辑:
即使人们不知道解决方案是什么,我仍然有兴趣知道他们是否可以重现错误。
编辑 2:
顺便说一下,这个问题不会在 Firefox 或 Safari 中持续存在。
如果您阅读与异常相关的完整错误消息,您将得到更好的解释:
❌ Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD
Google 的文章“Autoplay Policy Changes”(链接在上面的消息中)详细解释了这种情况。
简短的版本是:如果你想播放音频或视频,你需要等到用户点击页面上的东西。
我正在尝试播放音频文件(我试过很多)。都是mp3。 我已经在 MAMP localhost 上以及在浏览器中 运行 测试了以下内容。
我使用以下 javascript:
var testSound = new Audio();
testSound.src = "a.mp3"
setTimeout(testSound.play.bind(testSound),100)
这个returns错误:
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);
})
}
returns 没有 (""
)
但如果我现在转到控制台并简单地键入:
testSound.play()
声音正常播放。
即使我将第一个代码片段的第三行注释为:
//setTimeout(testSound.play.bind(testSound),100)
编辑:
即使人们不知道解决方案是什么,我仍然有兴趣知道他们是否可以重现错误。
编辑 2:
顺便说一下,这个问题不会在 Firefox 或 Safari 中持续存在。
如果您阅读与异常相关的完整错误消息,您将得到更好的解释:
❌ Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD
Google 的文章“Autoplay Policy Changes”(链接在上面的消息中)详细解释了这种情况。
简短的版本是:如果你想播放音频或视频,你需要等到用户点击页面上的东西。