-->

Pages

Tuesday 28 February 2017

JavaScript Code to Play,Pause and Mute Audio in HTML Page.

Have you ever feel wondered, how can I play audio in my HTML file without using the HTML5 <audio> tag. It is possible to play audio using javascript Audio Object, it contains all the predefined methods that make it easy for a user to control the playing audio with ease.
In this article of mine, I am providing the code snippet of Playing Audio in HTML page using Javascript.


Source: Google Images

Here is the code snippet(I am providing the JavaScript Code only):

CODE:

 <script>

var audio, playbtn, mutebtn;

function initAudioPlayer(){

audio = new Audio();
        //audio is a folder in my project and 1.mp3 is the file name
audio.src = "audio/1.mp3";
audio.loop = true;//this property is set to true to play the track continuosly
audio.play();//this will play the audio

// Set object references

playbtn = document.getElementById("playpausebtn");
mutebtn = document.getElementById("mutebtn");

// Add Event Handling on our buttons

playbtn.addEventListener("click",playPause);
mutebtn.addEventListener("click", mute);

// Functions
function playPause(){
/* checking if audio is already paused,
make it play and change the button text to PAUSE else if it already playing make it pause and change the button text to PLAY */

if(audio.paused){
   audio.play();
   playbtn.innerHTML="PAUSE";
   } else {
   audio.pause();
   playbtn.innerHTML="PLAY";
   }
}

function mute(){
// This function is designed to mute the audio if needed 

if(audio.muted){
   audio.muted = false;
   mutebtn.innerHTML="MUTE";
   } else {
   audio.muted = true;
   mutebtn.innerHTML = "SOUND";
   }
}
}

/*adding the event listener, to initialize all the component once the page is completely loaded*/

window.addEventListener("load",initAudioPlayer);

</script>

Make sure to add a couple of buttons in your HTML file like:


<button id="playpausebtn">PAUSE</button>

<button id="mutebtn">MUTE</button>

That's all it is a very simple code snippet to play audio in HTML, implement it by yourself and still have some doubt about it, then you can ask me.

No comments:

Post a Comment

Thanks for Your Time!