In previous posts, we learnt how to play audio in web page uisng HTML5, we also learnt how to create a custom adio player in HTML5. In this post, we will learn how to add a stoppable background audio player using HTML5.
Here is a css style for the pause button and the page. Here we simply set the background color and set the position of the button to fixed and at the bottom center of the page.
<style>
body{
background-color:#e09103;
}
#control{
position:fixed;
bottom:0%;
left:50%;
}
</style>
In below HTML5 code, we have an audio element with autoplay
and loop
attribute set. We also have a button to control the audio.
<audio src="954.mp3" id="audio1" autoplay loop>
Audio is not supported.
</audio>
<div id="content">
<h1>This is <i>TechFunda</i></h1>
<p style="font-size:18px;">To know the events details of multimedia elements of HTML5
To play audio in HTML5, we can use the tag which is introduced in HTML5. </p>
</div>
<div id="control">
<input type="button" id="btnPause" onclick="PausePlay()" style="padding:20px;" value="Pause" />
</div>
When page loads, the audio will keep playing untill user stops it by clicking on the Pause button displayed at the bottom center of the page.
In below code snippet, we have created two variables for audio and button. We have also declared the PausePlay() function that is called on click of the button. When the audio is playing, it pauses otherwise play the audio.
<script>
var audio = document.getElementById("audio1");
var btn = document.getElementById("btnPause");
function PausePlay() {
if (audio.paused) {
audio.play();
btn.value = "Pause";
} else if (audio.ended) {
audio.currentTime = 0;
audio.play();
btn.value = "Pause";
}
else {
audio.pause();
btn.value = "Play";
}
}
</script>
That's it. If you are looking for solution of how to play background video of the web page, click here.
Views: 14061 | Post Order: 104