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>

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

Leave a Comment