Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make audio play on body onload?

Yesterday I downloaded a responsive navbar tutorial and saw that the author had used button click sound using JavaScript.
So I try the code (copying it) and was able to make it too. When the button is clicked the background music plays well. But when I try adding the same code to body onload function the music din't play.

So, I thought the code has some error but suddenly I opened the HTML file from Opera Mini for Android and the background music appeared. The code which isn't working in advanced browsers like Chrome is working in Opera Mini. Why is this happening?

 <!DOCTYPE html>
 <head>
 <title>Untitled</title>
 <meta charset="UTF-8"/>
 <link rel="stylesheet" href="" type="text/css"/>
 <script>

 function stir0(){
 var bbs = new Audio('media/background.ogg');
 bbs.play();
 alert('bb');
 }

 function pl(){

  var Loops = new Audio('media/button_click.ogg');

 Loops.play();
  }


 </script>
 </head>
 <body onload="stir0()">
<button id="clk" onClick="pl()">Here</button>
 </body>
 </html>  
like image 609
Best Bibek Avatar asked Jan 01 '23 17:01

Best Bibek


1 Answers

As of April 2018, Google had changed their Autoplay Policy. It was implemented in Chrome v.66.

Relevant snippet from the Policy:

Chrome's autoplay policies are simple:

  • Muted autoplay is always allowed.

  • Autoplay with sound is allowed if:

    • User has interacted with the domain (click, tap, etc.).
    • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
    • On mobile, the user has added the site to their home screen.
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

The way I understand it, and it seems to be reflected in your experience: Chrome browser mutes any autoplayed audio if no action of the user had been made with the domain that specificly requests the audio to be played. Once a user has made a positive interaction, the rules soften and the media may be played without consent renewal.

like image 185
shuk Avatar answered Jan 13 '23 14:01

shuk