M Muneer
M Muneer

Reputation: 377

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

I tried to make html page with javascript to play sound on mouse over but when I tried the code on first reload on chrome browser it give me this error. How I can solve this issue in chrome.

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

<html>
<head>
    <title>ضمور العضلات</title>
    <style>
        .img-container {
            text-align: center;
        }
    </style>
 
    <!-- Font Awesome -->
   
</head>

<audio id="musicSound" preload="auto" src="disability/sounds/song.mp3"   
>
</audio>
<audio id="hungrySound" preload="auto" src="disability/sounds/water.mp3" 
>
</audio>
<body style="background: #E8E8E8;">


    <div class="container">
        <div class="row" style="margin-top: 30px;">
            <div class="col-md">
                <img id="thirsty"  onmouseover="playHungry()" src="disability/images/hungry_icon.png" class="img-thumbnail" title="أنا جائع">
            </div>
        
        </div>

        <div class="row" style="margin-top: 130px;">
            <div  class="col-md" >
                <img id="music" onmouseover="playMusic()" src="disability/images/music_icons.png" class="img-thumbnail" title="شغل الموسيقى">
            </div>
            

        </div>


    </div>

    <script>
        var music = document.getElementById("musicSound");
        var hungry= document.getElementById("hungrySound");
     

        function playMusic() {
            music.play();

            thirsty.pause();
            thirsty.currentTime = 0;
        }

       
        function playHungry() {
            hungry.play();

            music.pause();
            music.currentTime = 0;
           

        }

    </script>

</body>
</html>

Upvotes: 1

Views: 8571

Answers (1)

lissettdm
lissettdm

Reputation: 13078

I recommend you to create the audio node on onmouseover event:

HTML

<div class="container">
  <div class="row" style="margin-top: 30px;">
    <div class="col-md">
      <img id="thirsty" onmouseover="play('disability/sounds/water.mp3')" src="disability/images/hungry_icon.png" class="img-thumbnail" title="أنا جائع">
    </div>
  </div>
  <div class="row" style="margin-top: 130px;">
    <div class="col-md">
      <img id="music" onmouseover="play('isability/sounds/song.mp3')" src="disability/images/music_icons.png" class="img-thumbnail" title="شغل الموسيقى">
    </div>
 </div>
</div>
<script>
  const audio = document.createElement("audio");
  audio.muted = true;

  function play(src) {
    audio.pause();
    audio.muted = false;
    const source = document.createElement("source");
    source.src = src;
    audio.appendChild(source);
    audio.currentTime = 0;
    audio.play();
  }
</script>

Upvotes: 0

Related Questions