Javatpoint Logo
Javatpoint Logo

Controlling Playback of media using JavaScript

In our previous section, we learned how we can play audio and video content. Previously, we used the browser's built-in HTML controls for playing audio and video content. In this section, we will learn how we can create these controls ourselves using JavaScript. We will use the following steps to create custom control buttons to play, pause, and stop audio:

1) Remove controls property of audio tag and add JQuery mobile library

We will use the same project, and from the HTML code, we will remove the controls property. We will also add the JQuery mobile library by simply adding the CDN hosted files below the title.

2) Give an Id to the audio

Now, we will give an Id to our <audio> tag because JavaScript doesn't know anything about the HTML. We will give it an Id in the following way:

3) Create play, pause and stop button

We will now create three buttons in the user interface, i.e., play, pause, and stop. These buttons are created by using <button></button> tag in the body section of the HTML code. We will give an Id to each button to get them in the window.onload function.


Controlling Playback of media using JavaScript

4) Create window.onload function

Now, we will create a window.onload function. In this function, we will get the audio content using the Id, and in the same function, we will get all those three buttons that we have created in the user interface. In this function, we will get the audio content and buttons in the following way:

1) We first create a global variable player and store the audio content in it. We will get the audio content using the Id which we have given to the <audio></audio> tag in the following way:

2) We will get the play button using its Id and add a listener for calling anonymous function. This anonymous function will play the content available in the player.

3) We will get both the buttons in the same way and attach the listener with both the remaining buttons. For pausing the player content, the pause() function is available, but there is no stop() function to stop it. For this purpose, we will first use the pause() function, and then we will set the current time to 0 in the following way:

Complete Code:

Output:

Controlling Playback of media using JavaScript




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA