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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With