Jovani
Jovani

Reputation: 127

How to autoplay sound at javascript page?

I am developing a web system to monitor some values from a database, and I need to play some sound alert when a range of values is received. I've tried a lot of internet samples, but anyone works. The error returned is "uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first". The last try was with the code bellow:

<audio id="myAudio" muted="muted">
          <source src="./resources/sound/Alarm.mp3" type="audio/mp3">
        </audio>
<script>
alert(){
    let x = document.getElementById("myAudio");

    if(this.percentIntegral[0]>=70 && this.percentIntegral[0]<=80){
            //alert("play");
            x.play();
        }
    }
</script>

Upvotes: 0

Views: 152

Answers (1)

Dhaval Soni
Dhaval Soni

Reputation: 416

Thank you for asking this question, I am also suffered from this issue, You can not autoplay audio because the browser needed some interaction with a user after music will autoplay. It's the security purpose of the browser.

The user didn't interact with the document first. It only works when the user interacts with a browser.

You also can not jquery click into the browser. when the user scrolls up down or clicks to any button then after audio will work.

Upvotes: 1

Related Questions