We sometimes add background music on the page, allowing users to enable and disable background music themselves, especially multimedia pages created based on mobile html5. The HTML5 audio tag can obtain the playing status of the audio, you can click the button to close or enable background music. As follows:
View demo source code download
HTML
Create an HTML5 page, place tags, set the audio file source, and set loop playback. Prepare two images, indicating that the background music is enabled and paused. You can click.
Copy XML/HTML Code to clipboard
- Your browser does not support the audio tag.
-
Javascript
When we click the "Switch image" button, we call the javascript script, playPause () function. The function is used to determine the audio playback status. It is called if the audio has been stopped (paused. play () continues playing. If it is in the playing status, it is paused immediately. pause (). When two statuses are switched, the button image is updated in time. See the Code:
Copy the content to the clipboard using JavaScript 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 jQuery code is used, you can write as follows:
Copy the content to the clipboard using JavaScript Code
- "Music" src = "http://cctv3.qiniudn.com/zuixingfuderen.mp3" autoplay = "autoplay" loop = "loop"> your browser does not support audio labels.
- "Audio_btn"> "play.gif" width = "48" height = "50" id = "music_btn" border = "0">
- 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