
Control audio through JavaScript.
6 January, 2023
2
2
0
Contributors
Controlling the audio through JavaScript is not a complex task. I will show how to play and pause the audio by clicking the play button and changing the play icon to the pause icon.
What will be the result

The UI does not look that good. But here we will be mainly focusing on writing the JavaScript code. So, when the play button is clicked the music will play βΆοΈ, and clicking it again will pause βΈοΈ the music.
Let's create some starter files
HTML
In your project folder create an HTML file with the name index.html
Add the following code to it.
So this is a fundamental HTML code. Here for icons, I used
CSS
Now Create a style.css file and add the following CSS
Nothing much in this CSS as well. I used flexbox to align the icons inside the div element.
JAVASCRIPT
Now finally add a script.js file
Here we will write some code to play/pause the audio and change the play icon to pause.
Create two variables to store elements object. One for the play icon and another one for the audio.
Now add an event listener on the play button. So that clicking it will execute some operation.π€
Now we have to add code to change the icon and play the song inside the curly braces.
The icon element for the play button has two classes fa-play and fa-solid. To change it to a pause icon we have to remove fa-play and add a fa-pause class.
To play/pause the audio execute the play()/pause() function on the audio element.
If the song is playing on clicking the icon the song must be paused on clicking it again. So add an else block.
Now on clicking the play icon the audio will play and the icon will be changed as well.
Final JavaScript code
End π€
I want to thank everyone who took the time to read my first blog π. Please post your reviews.