lundi 19 avril 2021

play() can be initiated by user gesture only

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.




Aucun commentaire:

Enregistrer un commentaire