In this article we will learn to create a play/pause buton for an audio file using ReactJS
Approach: We are going to use the following steps:
- Take the reference of the audio file in ReactJS Using Audio Class
- Set the default state of the song as not playing.
- Make a function to handle the Play/Pause of the song.
- Use the play() and pause() functions of audio class to do these operations.
let song = new Audio(my_song); song.play(); song.pause();
Setting up environment and Execution:
Step 1: Create React App command
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
Step 3: Create a Static folder and add an audio file to it.
Project Structure: It will look like the following.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, Turn on speakers to listen to audio.