简体   繁体   中英

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>  

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.

You can do the first one (the background music) with pure HTML:

<audio autoplay>
    <source src="media/background.ogg" type="audio/ogg">
</audio>

The second one (the button click) you do like this:

//JS
var Loops = new Audio("media/button_click.ogg");
//Make sure this is a GLOBAL variable.

And in HTML:

<!--HTML-->
<button id="clk" onClick="Loops.play()">Here</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM