Search code examples
javascriptjqueryhtml5-audio

`.play()` failed because the user didn't interact with the document first issue


I want to play sound, after my page has loaded.

Here is my JavaScript code:

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

Here is my HTML code:

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

Console output:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.


Solution

  • Most browsers block any audio that is played by a web page and is not related to user interaction (see https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide). With user interaction I mean things like pressing a button. You can't do anything against that.

    But you could add a start button that displays the page and starts the music, like this:

    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>