Pol*_*nce 12 javascript audio html5 asynchronous html5-audio
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.
I use the following javascript:
var testSound = new Audio();
testSound.src = "a.mp3"
setTimeout(testSound.play.bind(testSound),100)
Run Code Online (Sandbox Code Playgroud)
This returns the error:
Uncaught (in promise)
Run Code Online (Sandbox Code Playgroud)
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);
})
}
Run Code Online (Sandbox Code Playgroud)
returns nothing ("")
But if I now turn to the console and simply type:
testSound.play()
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
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:
By the way, the problem doesn't persist in Firefox or Safari.
dus*_*uff 22
如果您阅读与异常相关的完整错误消息,则将得到更好的解释:
?未捕获(承诺)的DOMException:play()失败,因为用户没有首先与文档进行交互。https://goo.gl/xX8pDD
Google的文章“ 自动播放政策更改 ”(在上面的消息中链接)详细说明了这种情况。
简短的版本是:如果要播放音频或视频,则需要等到用户单击页面上的某些内容后再进行操作。