不断出错 - 尝试播放音频时 - 为什么?

时间:2021-01-16 21:04:39

标签: javascript audio

当我尝试使用下面的 Js 在我的 chrome book 上播放音频时,我不断收到这条消息:

“DOMException: play() 失败,因为用户没有先与文档交互。”

<script>  
      window.addEventListener('load', (event) => {  
        console.log('page is fully loaded');  
         
        console.log('playing music');  
          
        var audioElement = new Audio('indie.mp3').play();  
  
        if (audioElement !== undefined) {  
          audioElement.then(_ => {  
            // Autoplay started!  
          }).catch(error => {  
            // Autoplay was prevented.  
            // Show a "Play" button so that user can start playback.  
            console.log(error);  
          });  
        }  
  
         
      });  
</script>

1 个答案:

答案 0 :(得分:1)

进行 Web 开发时的第一条规则是 show your browser console ...一旦你这样做,当我运行你的代码时,我看到以下控制台错误(你会看到一个错误,措辞类似于我在 firefox 其他浏览器显示不同的措辞)

<块引用>

DOMException: 当前上下文中用户代理或平台不允许播放方法,可能是因为用户拒绝了权限。

在英语中,这意味着网页会在未经最终用户许可的情况下尝试在加载时立即播放音频......几年前,行业对自动播放音频的网页进行了强烈反对,因此所有浏览器都同意阻止自动播放的代码音频...下面的作品,一旦你点击按钮就会播放音频

<!DOCTYPE html>
<html>

    <!-- https://www.w3schools.com/jsref/met_audio_play.asp -->
    <!-- https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_audio_play -->
    <!-- http://www.html5rocks.com/en/tutorials/webaudio/intro/ -->
    <head>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
    </head>
    <body>
        <audio id="myAudio">
            <!-- <source src="horse.mp3" type="audio/mpeg" /> -->
            <!-- above also works if mp3 file is local to same dir as this html file  -->
            <source src="https://www.w3schools.com/jsref/horse.mp3" type="audio/mpeg">

            Your browser does not support the audio element.
        </audio>

        <button onclick="playAudio()" type="button">Play Audio</button>
        <button onclick="pauseAudio()" type="button">Pause Audio</button>

        <script>
            var x = document.getElementById("myAudio");

            function playAudio() {
                x.play();
            }

            function pauseAudio() {
                x.pause();
            }
        </script>
    </body>
</html>

以上代码取自作为评论嵌入的链接...... webdev 是一个流动的工作体,因此从符合当今现实的当前教程中推动学习非常重要......享受并欢迎音频处理

相关问题