For the automatic playback of background music in HTML5, html5 automatically plays
The automatic playback attribute of music is described as follows:
<audio controls="controls" autoplay="autoplay"> <source src="song.ogg" type="audio/ogg" /> <source src="song.mp3" type="audio/mpeg" />Your browser does not support the audio element.</audio>
The autoplay attribute specifies that playback starts immediately once the audio is ready.
If this attribute is set, the audio is automatically played.
However, in actual use, automatic playback is often not possible, mainly because some browsers or mobile phones will block or do not support the autoplay attribute. Here I will introduce my methods.
First, the code in html is as follows:
<Audio id = "music1" controls = "controls" autoplay = "autoplay" preload id = "music1" hidden> <source src = "music/bgmusic.pdf"/> </audio> <! -- Here is music --> <! -- Here is a switch that can control the pause of playing background music -->
Use the following code in the js file:
Var audio = document. getElementById ('music1'); $ ("# btn"). bind ("touchstart", function bf () {if (audio! = Null) {// checks whether the playback has been paused. audio. paused returns false during player playback. // alert (audio. paused); if (audio. paused) {audio. play (); // audio. play (); // This is playing $ ("# btn "). addClass ("active")} else {audio. pause (); // This is the pause $ ("# btn "). removeClass ("active ")}}})
After writing this, most Android devices can basically achieve automatic playback, but Apple mobile phones still won't work at this time.
Here I use a button to add to the loading page. When the loading is complete, click the button to guide the user to play the background music automatically. The Code is as follows:
$("html").one('touchstart',function(){audio.play();})
Now, the background music is automatically played. This method applies to loading pages and you need to click to enter the h5 project ......
Summary
The above section describes the automatic playback function of background music in HTML5. I hope it will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!