How to toggle play/pause in ReactJS with audio ?
In this article, we will learn to create a play/pause button for an audio file using ReactJS.
Prerequisites:
Approach:
- 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 the audio class to do these operations.
let song = new Audio(my_song);
song.play();
song.pause();
Steps to Create the React Application And Installing Module:
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:
cd foldername
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Now write down the following code in the App.js file.
Javascript
import React, { Component } from "react" ;
import song from "./static/a.mp3" ;
class App extends Component {
state = {
audio: new Audio(song),
isPlaying: false ,
};
playPause = () => {
let isPlaying = this .state.isPlaying;
if (isPlaying) {
this .state.audio.pause();
} else {
this .state.audio.play();
}
this .setState({ isPlaying: !isPlaying });
};
render() {
return (
<div>
{ }
<p>
{ this .state.isPlaying ?
"Song is Playing" :
"Song is Paused" }
</p>
{ }
<button onClick={ this .playPause}>
Play | Pause
</button>
</div>
);
}
}
export default App;
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000
Last Updated :
29 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...