我正在尝试播放音频文件(我尝试了很多)。它们都是mp3。
我已经在MAMP本地主机上以及通过仅在浏览器中运行它测试了以下内容。
我使用以下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()
声音按预期播放。
即使我将第一个代码段的第三行注释为:
//setTimeout(testSound.play.bind(testSound),100)
编辑:
即使人们不知道解决方案是什么,我仍然想知道他们是否可以重现错误。
编辑2:
顺便说一句,该问题不会在Firefox或Safari中持续存在。
最佳答案
如果您阅读与异常相关的完整错误消息,则将得到更好的解释:
Google的文章“Autoplay Policy Changes”(在上面的消息中链接)详细说明了这种情况。
简短的版本是:如果要播放音频或视频,则需要等待直到用户单击页面上的某些内容为止。