Auto-Playback of h5 background music

Source: Internet
Author: User

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 ......

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.