wnq
wnq

Reputation: 25

Autoplay music on chrome

I have found only deprecated anwers so i need to ask how to make autoplay on chrome?

<audio autoplay loop controls src="./audio/menu.wav" data-start-screen-audio></audio>

let music = new Audio("./audio/menu.wav");
music.addEventListener("canplaythrough", function () {
    music.play();
});

these two metods works on other browsers but on chrome not, how to fix that?

Upvotes: 0

Views: 2787

Answers (2)

Joseph
Joseph

Reputation: 6269

by default in modern browser, this is not allowed but if you add the muted attribute it will work fine

as they mention here in mdn

Note: Sites that automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, this can be useful when creating media elements whose source will be set at a later time, under user control.

but in the case of media content you could run the play action from js like this

<video src="" id="videoEl">

document.onload = function(){
  document.getElementById('videoEL').play()
}

for more info check the autoplay guide

Upvotes: 1

Ashutosh Patole
Ashutosh Patole

Reputation: 980

You may simply use (.autoplay = true;) as following (tested on Chrome Desktop):

<audio id="audioID" loop> <source src="path/audio.mp3"  type="audio/mp3"></audio>
    
<script>
    var myaudio = document.getElementById("audioID").autoplay = true;
</script>

Upvotes: 0

Related Questions