Using HTML5 to control the background music switch with buttons

Time:2021-11-28

The renderings are as follows:

View demo results    Source download

HTML

Create an HTML5 page, place the < audio > tag, set the audio file source, and set loop playback. Prepare two pictures to indicate the two states of opening and pausing background music respectively, which can be clicked.
 
XML/HTML CodeCopy contents to clipboard

  1. <audio id=“music2” src=“music.mp3”  loop=“loop”>Your browser does not support audio tags.</audio>    
  2. <a href=“javascript:playPause();”><img src=“pause.gif” width=“48” height=“50” id=“music_btn2” border=“0”></a>  

Javascript

When we click the switch picture button, we call the JavaScript script and the playpause () function. Judge the audio playing status in the function. If it has stopped (paused), call. Play() to continue playing. If it is in the playing status, pause playing immediately. Pause(). When the two states are switched, update the button picture in time. See the code:
 JavaScript CodeCopy contents to clipboard

  1. function playPause() {    
  2.     var music = document.getElementById(‘music2’);    
  3.     var music_btn = document.getElementById(‘music_btn2’);    
  4.     if (music.paused){    
  5.         music.play();    
  6.         music_btn.src = ‘play.gif’;    
  7.     }    
  8.     else{    
  9.         music.pause();    
  10.         music_btn.src = ‘pause.gif’;     
  11.     }    
  12. }   

If you use jQuery, the code can be written as follows:
 
JavaScript CodeCopy contents to clipboard

  1. <audio id=“music” src=“http://cctv3.qiniudn.com/zuixingfuderen.mp3” autoplay=“autoplay” loop=“loop”>Your browser does not support audio tags</ audio>
  2. <a id=“audio_btn”><img src=“play.gif” width=“48” height=“50” id=“music_btn” border=“0”></a>    
  3. <script>    
  4. $(“#audio_btn”).click(function(){    
  5.     var music = document.getElementById(“music”);    
  6.     if(music.paused){    
  7.         music.play();    
  8.         $(“#music_btn”).attr(“src”,“play.gif”);    
  9.     }else{    
  10.         music.pause();    
  11.         $(“#music_btn”).attr(“src”,“pause.gif”);    
  12.     }    
  13. });    
  14. </script>