Home » How To Build Audio Player in React JS

How To Build Audio Player in React JS

how to build audio player in react js

In this blog post, we will build an Audio player component in React JS. The component will allow users to play, pause, seek through audio, and view the audio’s current time and duration.

As you can see in the above demo video, we have a simple audio player card. It contains a cover image, an input range element to see through the audio, and a play and pause button.

Defining the AudioPlayer component

First, we’ll create our `AudioPlayer` component that takes a single prop `audioSrc`. The `audioSrc` prop is the source of the audio file that we want to play in our player.

function AudioPlayer({ audioSrc }) {
    // ...
    return (
        // ...
    );
}
 
export default AudioPlayer;

Define state variables for the audio player

const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);

Here, `isPlaying` is a boolean that determines whether the audio is playing. The `currentTime` state variable stores the current time of the audio playback, and `duration` is the total duration of the audio file. We set the initial state of `isPlaying` to `false`, and `currentTime` and duration to 0.

We also create a reference to the audio element using the useRef hook:

const audioRef = useRef(null);

The `audioRef` variable is initialized to `null` and will reference the audio element in the DOM once the component has mounted.

Defining event handlers to play, pause, and toggle the audio

Next, we define some functions that will handle the play, pause, and play/pause toggle events of the audio player:

  const handlePlay = () => {
    audioRef.current.play();
    setIsPlaying(true);
  };

  const handlePause = () => {
    audioRef.current.pause();
    setIsPlaying(false);
  };

  const handlePlayPause = () => {
    if (isPlaying) {
      handlePause();
    } else {
      handlePlay();
    }
  };

These functions are used to control the behavior of the audio player. `handlePlay` plays the audio, `handlePause` pauses the audio, and `handlePlayPause` toggles the audio between playing and paused states.

Defining an event handler to update the time and duration of the audio

We also define a function `handleTimeUpdate` that will be called whenever the `timeupdate` event is triggered on the audio element:

const handleTimeUpdate = () => {
  setCurrentTime(audioRef.current.currentTime);
  setDuration(audioRef.current.duration);
};

The `handleTimeUpdate` function sets the current time and duration of the audio playback by updating the `currentTime` and `duration` state variables.

Defining an event handler to seek to a specific time in the audio

const handleSeek = (e) => {
   audioRef.current.currentTime = e.target.value;
   setCurrentTime(e.target.value);
};

The `handleSeek` function is called when the user drags the seek bar to a specific time in the audio file. It updates the `currentTime` variable and seeks to the specified time.

Defining a function to format the duration of the audio

function formatDuration(durationSeconds) {
  const minutes = Math.floor(durationSeconds / 60);
  const seconds = Math.floor(durationSeconds % 60);
  const formattedSeconds = seconds.toString().padStart(2, "0");
  return `${minutes}:${formattedSeconds}`;
}

The `formatDuration` function takes the duration of the audio in seconds and formats it into minutes and seconds. It pads the seconds with a zero if it is a single-digit number.

Using the useEffect hook to add and remove an event listener

  useEffect(() => {
    audioRef.current.addEventListener("timeupdate", handleTimeUpdate);
    return () => {
      audioRef.current.removeEventListener("timeupdate", handleTimeUpdate);
    };
  }, []);

This useEffect hook adds an event listener to the audio element when the component mounts and removes it when the component unmounts. The event listener listens for changes in the time

JSX code to render audio player

return (
    <div className="player-card">
      <img src="./assets/cover-image.jpg" alt="Cover Image" />

      <input
        type="range"
        min="0"
        max={duration}
        value={currentTime}
        onChange={handleSeek}
      />

      <audio ref={audioRef} src={audioSrc} />

      <div className="track-duration">
        <p>{formatDuration(currentTime)}</p>
        <p>{formatDuration(duration)}</p>
      </div>

      <button onClick={handlePlayPause}>
        <span class="material-symbols-rounded">
          {isPlaying ? "pause" : "play_arrow"}
        </span>
      </button>
    </div>
  );

The above JSX code renders a player card that contains an image, an HTML audio element, a range input for seeking, and a button for playing or pausing the audio. It also displays the current time and duration of the audio.

Also, check out:

Complete Code of `AudioPlayer` component:

import React, { useState, useRef, useEffect } from "react";

function AudioPlayer({ audioSrc }) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const audioRef = useRef(null);

  const handlePlay = () => {
    audioRef.current.play();
    setIsPlaying(true);
  };

  const handlePause = () => {
    audioRef.current.pause();
    setIsPlaying(false);
  };

  const handlePlayPause = () => {
    if (isPlaying) {
      handlePause();
    } else {
      handlePlay();
    }
  };

  const handleTimeUpdate = () => {
    setCurrentTime(audioRef.current.currentTime);
    setDuration(audioRef.current.duration);
  };

  const handleSeek = (e) => {
    audioRef.current.currentTime = e.target.value;
    setCurrentTime(e.target.value);
  };

  function formatDuration(durationSeconds) {
    const minutes = Math.floor(durationSeconds / 60);
    const seconds = Math.floor(durationSeconds % 60);
    const formattedSeconds = seconds.toString().padStart(2, "0");
    return `${minutes}:${formattedSeconds}`;
  }

  useEffect(() => {
    audioRef.current.addEventListener("timeupdate", handleTimeUpdate);
    return () => {
      audioRef.current.removeEventListener("timeupdate", handleTimeUpdate);
    };
  }, []);

  return (
    <div className="player-card">
      <img src="./assets/cover-image.jpg" alt="Cover Image" />

      <input
        type="range"
        min="0"
        max={duration}
        value={currentTime}
        onChange={handleSeek}
      />

      <audio ref={audioRef} src={audioSrc} />

      <div className="track-duration">
        <p>{formatDuration(currentTime)}</p>
        <p>{formatDuration(duration)}</p>
      </div>

      <button onClick={handlePlayPause}>
        <span class="material-symbols-rounded">
          {isPlaying ? "pause" : "play_arrow"}
        </span>
      </button>
    </div>
  );
}

export default AudioPlayer;

Using The `AudioPlayer` component in App.js

import React from "react";
import AudioPlayer from "./AudioPlayer";

const AUDIO_FILE = "URL_OF_AUDIO_FILE";

function App() {
  return (
    <div className="container">
      <AudioPlayer audioSrc={AUDIO_FILE} />
    </div>
  );
}

export default App;

Output:

audio player in react with example

Conclusion

That’s it, we have created an audio player component in React JS that allows users to play, pause, seek through audio, and view the audio’s current time and duration. Hope it was helpful.

Leave a Reply

Your email address will not be published.