html autoplay not working properly in chrome

Viewed 626

while I am trying to autoplay a song in chrome but it is not working. I tried using JavaScript still getting the same error.

function myFunction() {
  var x = document.getElementById("myAudio").autoplay;
  document.getElementById("demo").innerHTML = x;
}

myFunction();
<audio id="myAudio" controls autoplay>
  <source src="https://www.w3schools.com/tags/horse.mp3" type="audio/mp3">
  Your browser does not support the audio element.
</audio>

<div id="demo"></div>

2 Answers

In most browsers you can only use autoplay with the muted attribute

See: https://www.w3schools.com/tags/att_audio_autoplay.asp

Note: Chromium browsers do not allow autoplay in most cases. However, muted autoplay is always allowed.

So something like this should work:

<audio id="myAudio" controls autoplay muted>
  <source src="horse.mp3" type="audio/mp3">
  Your browser does not support the audio element.
</audio>

It is not allowed to autoplay sounds. So it has to be muted. Also with video you have to mute it, otherwise the video is not played. So it will be with audio also. Maybe you have to add a button that says that they have to click it to hear the sound?

Related