The “play()” method plays the current audio, and the “pause()” method stops the audio being played. These methods can be applied to play and pause the associated audio with the help of a user-defined function.
Let’s overview the below-stated example:
In the above code lines:
- Firstly, include an “<audio>” element along with the “audio” attribute that allows to include the play, and pause controls.
- After that, include a “<source>” element to attach the audio file and specify the type of the file in the “type” attribute.
- In the next step, create two buttons with attached “onclick” events invoking the stated functions to play and pause the audio file.
- Then, define a function named “playAudio()”.
- In its definition, apply the “play()” method to play the associated audio.
- Likewise, declare a function “pauseAudio()”, and the “pause()” method in its definition will similarly pause the corresponding audio.
In the output, it can be seen that the included audio is being played and paused properly.
In this method, the “autoplay” property enables the audio as soon as it is loaded. This property can be utilized to play the corresponding audio upon being loaded.
The below-stated example illustrates the stated concept:
In the above code block:
- Likewise, create two buttons with an “onclick” event redirecting to the functions playAudio() and pauseAudio(), respectively.
- After that, define a function named “playAudio()”.
- In its definition, it generates an alert to notify the playing of audio.
- In the next step, the “src” attribute specifies the audio path.
- The “autoplay” property indicates that the audio will play when the function becomes invoked.
- “loop” property defines that the audio file will be played till the next action.
- Lastly, similarly, declare a function named “pauseAudio()”.
- In its definition, display an alert dialogue box referring to a notification before the audio is paused.
The above output indicates that upon clicking the buttons, the audio has been played and paused appropriately.