Use the button to control the HTML5 background music switch

Source: Internet
Author: User


We sometimes add a background music to the page, allowing the user to turn on and off the background music, especially based on the mobile phone HTML5 made of multimedia pages, HTML5 audio audio tags can get audio playback status, through the touch button can turn off and open the background music.


Create a HTML5 page, place <audio> tag, set audio file source, set loop playback. Prepare two pictures, respectively, to open and pause the background music of two states, you can click.

<audio id= "Music2" src= "Music.mp3" loop= "loop" > your browser does not support audio tags. </audio>

<a href= "Javascript:playpause ();" ></a>


We called the JavaScript script, the Playpause () function, when we clicked on the Toggle Picture button. function to determine the audio audio playback state, if it has been stopped (paused), call. Play () continue playing, and if it is playing, pause playback immediately. Pause (), when the two states switch time to update the button picture, please see the code:

function Playpause () {

var music = document.getElementById (' Music2 ');

var music_btn = document.getElementById (' music_btn2 ');        

if (music.paused) {

music.play ();

MUSIC_BTN.SRC = ' play.gif ';    

} 

else{

music.pause ();

MUSIC_BTN.SRC = ' pause.gif ';

} 

}

If you use jquery code to write this:

<audio id= "Music"  src= "http://cctv3.qiniudn.com/" Zuixingfuderen.mp3 " autoplay=" AutoPlay " loop=" loop "> your browser does not support audio tags. </audio>  <a id= "audio_btn" ></a>    <script>  $ ("#audio_btn"). Click (

function () {      var music = document.getelementbyid ("Music");      if (music.paused) {          music.play ();           $ ("#music_btn"). attr ("src", "play.gif");       }else{          music.pause ();           $ ("#music_btn"). attr ("src", "pause.gif");        });  </script> 

The


Note is to remember to load the jquery library file.

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.