Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Uncaught (in promise) DOMException while playing AUDIO

Chrome blocks auto-playing audio/video. I've found solutions for auto-playing video, but my use case requires auto-playing audio. Here is my code:

let audio = new Audio('music/test.mp3'); audio.play(); audio.loop = true;

This results in an "Uncaught (in promise) DOMException" on Chromium browsers because of new policies.

like image 495
S M Avatar asked Feb 16 '19 02:02

S M


2 Answers

You're receiving an uncaught exception because you aren't handling an error.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play

Audio is an HTMLMediaElement object, and the play() method returns a promise. Therefore I recommend handling the error.

var promise = audio.play();
if (promise) {
    //Older browsers may not return a promise, according to the MDN website
    promise.catch(function(error) { console.error(error); });
}

One of two errors are possible:

NotSupportedError

This means that the audio source is not supported by the browser (probably due to audio format)

NotAllowedError

This is the one I suspect you are triggering. This means the user needs to explicitly trigger the audio.play(), so the method is only usable if it is in response to a user generated event such as a click event.

Docs:

The user agent (browser) or operating system doesn't allow playback of media in the current context or situation. This may happen, for example, if the browser requires the user to explicitly start media playback by clicking a "play" button.

like image 98
Norman Breau Avatar answered Nov 09 '22 07:11

Norman Breau


The browser requires the user to explicitly start media playback by clicking a "play" button. Code below solves your problem.

<!DOCTYPE html>
<html>
<head>
<title>Play MP3 music on web</title>
<script>
function playMusic(){
    var promise = document.querySelector('audio').play();
    if (promise !== undefined) {
        promise.then(_ => {
            // Autoplay started!
        }).catch(error => {
            // Autoplay was prevented. Show a "Play" button so that user can start playback.
        });
    }
}
</script> 
</head>  
<body>
    <p>Play MP3</p>
    <input type="button" value="play music" onClick="playMusic();">
    <audio loop id="sound">
        <source src="audio/audio.mp3" type="audio/mpeg">
        <p>Browser doesn't support html5</p>
    </audio>
</body>
</html>
like image 40
Kardi Teknomo Avatar answered Nov 09 '22 08:11

Kardi Teknomo