Skip to content
Related Articles

Related Articles

Improve Article
How to toggle play/pause in ReactJS with audio ?
  • Last Updated : 21 Apr, 2021

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:



    cd foldername
  • Step 3: Create a Static folder and add an audio file to it.

Project Structure: It will look like the following.

Example:

App.js




import React, { Component } from "react";
  
// Import your audio file
import song from "./static/a.mp3";
  
class App extends Component {
  // Create state
  state = {
  
    // Get audio file in a variable
    audio: new Audio(song),
  
    // Set initial state of song
    isPlaying: false,
  };
  
  // Main function to handle both play and pause operations
  playPause = () => {
  
    // Get state of song
    let isPlaying = this.state.isPlaying;
  
    if (isPlaying) {
      // Pause the song if it is playing
      this.state.audio.pause();
    } else {
  
      // Play the song if it is paused
      this.state.audio.play();
    }
  
    // Change the state of song
    this.setState({ isPlaying: !isPlaying });
  };
  
  render() {
    return (
      <div>
        {/* Show state of song on website */}
        <p>
          {this.state.isPlaying ? 
            "Song is Playing"
            "Song is Paused"}
        </p>
  
        {/* Button to call our main function */}
        <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/, Turn on speakers to listen to audio.




My Personal Notes arrow_drop_up
Recommended Articles
Page :