Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use HTML5 to control the background music switch with buttons

Shulou Source: shulou.com Published: 2022-06-01 11:23:18 10月31日 Update

Xiaobian to share with you how to use HTML5 to achieve the use of buttons to control the background music switch, I believe most people do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

We sometimes add background music to the page, allowing users to turn on and off background music themselves, especially multimedia pages based on mobile html5, HTML5 audio tag can get audio playback status, and background music can be turned off and on by touching buttons.

Create an HTML5 page, place tags, set audio file sources, set loop playback. Prepare two pictures, respectively, indicating that the background music on and pause two states, you can click.

Your browser does not support frames.

Javascript

We called the javascript script, playPause() function when we clicked the switch picture button. Function to determine the audio playback status, if it has stopped (paused) then call.play() to continue playing, if it is in the playback state, then immediately pause playback.pause(), two state switch timely update button picture, please see the code:

JavaScript Code Copy content to clipboard

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, you can write:

Your browser does not support frames.

$("#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");

}

});

The above is "how to use HTML5 to achieve the use of buttons to control background music switch" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Background background music music buttons status tags audio content pictures articles pages controls code functions browsers support browsing not much clipboard multimedia Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Linux Shulou Information NVidia MySQL