Auto-Playback of h5 background music
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 --> In the js file, use the following code 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") }}) is written here, and most Android devices can basically achieve automatic playback, however, the Apple mobile phone still does not 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 enables automatic playing of background music. This method applies to loading pages and you need to click to enter the h5 project ......