js播放声音出现uncaught (in promise) DOMException: play() failed because the user didn't interact with the
今天通过js来播放audio,结果报错
uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="text/javascript"> window.onload = function() { var myAudio = document.createElement('audio'); myAudio.autoplay = true; myAudio.src = "//repo.bfw.wiki/bfwrepo/sound/5d7caa4c450fd.mp3"; } var audio = new Audio(); audio.src = '//repo.bfw.wiki/bfwrepo/sound/5d7caa4c450fd.mp3'; // when the sound has been loaded, execute your code audio.oncanplaythrough = (event) => { var playedPromise = audio.play(); if (playedPromise) { playedPromise.catch((e) => { console.log(e) if (e.name === 'NotAllowedError' || e.name === 'NotSupportedError') { console.log(e.name); } }).then(() => { console.log("playing sound !!!"); }); } } </script> </body> </html>