【问题标题】:play() failed because the user didn't interact with the document first issueplay() 失败,因为用户没有与文档第一个问题进行交互
【发布时间】:2020-11-20 12:47:19
【问题描述】:

我想在我的页面加载后播放声音。 这是我的javascript代码:

var playAudio = $("#sound")[0];
playAudio.play();

和html代码:

<audio id="sound">
        <source src="../music/hide.ogg" type="audio/ogg">
        <source src="../music/hide.mp3" type="audio/mp3">
</audio>

控制台: Uncaught (in promise) DOMException: play() failed 因为用户没有先与文档交互。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    大多数浏览器会阻止网页播放的任何与用户交互无关的音频(请参阅https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide)。对于用户交互,我的意思是按下按钮之类的事情。对此你无能为力。

    但您可以添加一个开始按钮来显示页面并开始播放音乐,如下所示:

    const startbtn = document.getElementById("startbtn");
    const content = document.getElementById("content");
    const loader = document.getElementById("loader");
    const music = document.getElementById("music");
    
    //Add an event listner to the start button
    startbtn.addEventListener("click", () => {
      //Show the loader and hide the button
      loader.style.display = "";
      startbtn.style.display = "none";
      //Wait for the music to start
      music.play().then(() => {
        //Hide the loader and show the content
        content.style.display = "";
        loader.style.display = "none";
      });
    });
    <!-- The start button --->
    <button id="startbtn">Start</button>
    
    <!-- The actual content, hidden by default -->
    <div id="content" style="display: none;">
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
      <p>Bla</p>
    </div>
    
    <!-- This is displayed when the user has pressed the start button, but the music is still loading -->
    <div id="loader" style="display: none;">
      <p>Loading ...</p>
    </div>
    
    <!-- The music. It is started by the Javascript -->
    <audio id="music" src="https://opengameart.org/sites/default/files/audio_preview/swing_0.mp3.ogg" style="display: none;" loop></audio>

    【讨论】:

    • 我想做一些事情,比如当我进入一个网站时,音乐正在播放,但如果用户想停止,所以他只需按下一个按钮。我可以这样做吗?如何?
    • 不,浏览器会自动屏蔽音频。但是您可以在加载网站时只显示一个开始按钮,并在按下开始按钮时显示整个页面并播放音乐。但我不知道这是否适合您的情况。
    • 如何在网站加载前制作按钮?
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多