0

I was trying to make a audio file start automatically when my website loads. I discovered that autoplay attribute was not working. So I used javascript but it doesn't work, rather it showed that play() can be initiated vy user gesture only.

My code:

<script type="text/javascript">
    function main() {
       var audioElement0 = document.createElement('audio');
       audioElement0.setAttribute('src', './audio.mp3');
       audioElement0.setAttribute('autoplay', 'autoplay');
       audioElement0.play(); 
       audioElement0.addEventListener('ended', function() {
       this.currentTime = 0;
       this.play();
       }, false);
    }
</script>
<body onload="main()">
   <button onclick="main()" id="btn" >play</button>
</body>

Please make me a complete script.

Liberty
  • 1
  • 3

1 Answers1

0

Are you sure your code looks like this:

<!DOCTYPE html>
<html>
<body>
<audio controls autoplay>
  <source src="src.mp3" type="audio/ <!--the type-->">
</audio>
</body>
</html>

If so, your browser just doesn't support autoplay, so use another one, certain browsers do, like Chrome, IE, Firefox, Safari, and Opera GX.

Alternatively, you can use:

<iframe src="src.mp3" allow="autoplay" id="audio"></iframe>
1BL1ZZARD
  • 225
  • 2
  • 14