Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to play audio as an alert but I'm getting an error like "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

HTML Code:

<audio id="alarm" src="alarm.mp3"></audio>

JavaScript Code:

function alarm() {
    var value = document.getElementById("rvoltage").innerHTML;
    if (value > 230) {
        document.getElementById('alarm').play();
    }
}
like image 698
Krishna Mohan Avatar asked Oct 24 '18 07:10

Krishna Mohan


1 Answers

That is due to the fact that many browsers do not allow HTML elements to autoplay music and videos on page-load to save bandwidth etc. You could create a button and play the music on a click event or hack your way around it to make it play on any click event on your page.

Autoplay with sound is allowed if: User has interacted with the domain (click, tap, etc.). On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound. On mobile, the user has [added the site to their home screen].

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

like image 166
Olaf Avatar answered Nov 02 '22 04:11

Olaf