Building a Custom Audio Player in React: A Step-by-Step Guide

Building a Custom Audio Player in React: A Step-by-Step Guide

Introduction: In this weblog, we’re constructing a easy but highly effective audio participant part in React. With the flexibility to play, pause, cease, and skip audio, this part leverages React hooks and interactive icons to create a seamless audio expertise. Let’s dive into every half and discover ways to combine this audio participant in any undertaking that makes use of audio in base64 format.

custom audio player

Component Breakdown

This PlayStory part makes use of React Icons for play, pause, skip, and cease buttons. It additionally handles audio state and playback utilizing useState and useEffect hooks.

import {
  IoPlayCircleOutline,
  IoPauseCircleOutline,
  IoStopCircleOutline,
  IoPlaySkipBackCircleOutline,
  IoPlaySkipForwardCircleOutline,
} from "react-icons/io5";

These imported icons give the participant a clear, accessible design. Let’s go over every main half:

Install react-icon from npm retailer

npm i react-icons

1. Component Initialization

The PlayStory part receives an audio prop in base64 format. This is transformed right into a playable audio file contained in the useEffect hook. The taking part in state determines whether or not the audio is at the moment taking part in or paused, whereas period and presentTime deal with the audio’s whole time and present time show.

Key states:

  • taking part in: Boolean, toggles audio play and pause.
  • audioFile: Holds the created audio file object.
  • period: Stores formatted whole period of the audio.
  • presentTime: Stores formatted time of the present playback place.

2. Formatting Audio Time

The formatTime operate converts uncooked audio seconds into an "MM
" format. This is used to indicate period and presentTime for a greater person expertise.

const formatTime = (seconds) => {
  const minutes = Math.flooring(seconds / 60);
  const remainingSeconds = Math.flooring(seconds % 60);
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
};

3. Audio Controls

This part comes with important playback controls:

  • Play/Pause Toggle
    The deal withPlayPause operate toggles between taking part in and pausing the audio based mostly on the taking part in state. When paused, it stops audio playback; when performed, it resumes.

  • Stop
    The deal withStop operate stops the audio, units presentTime to the start, and resets the taking part in state.

  • Skip Back/Forward
    The deal withSkipBack and deal withSkipForward features permit customers to leap again or ahead by 10 seconds within the audio.

const deal withPlayPause = () => {
  if (audioFile) {
    if (taking part in) {
      audioFile.pause();
    } else {
      audioFile.play();
    }
    isPlaying((pre) => !pre);
  }
};

const deal withStop = () => {
    audioFile.pause();
    audioFile.presentTime = 0;
    isPlaying(false);
  };

  const deal withSkipBack = () => {
    const newTime = audioFile.presentTime - 10;
    audioFile.presentTime = newTime < 0 ? 0 : newTime;
  };

  const deal withSkipForward = () => {
    const newTime = audioFile.presentTime + 10;
    audioFile.presentTime =
      newTime > audioFile.period ? audioFile.period : newTime;
  };

4. State to be handle for participant

 const { base64audio } = props; // get the audio information in base64
  const [playing, isPlaying] = useState(false);
  const [audioFile, setAudioFile] = useState(null);
  const [duration, setDuration] = useState("00:00");
  const [currentTime, setCurrentTime] = useState("00:00");

5. Managing Audio Playback with Hooks

Two useEffect hooks are used for:

  • Setting up the audio file from the base64 prop, and setting period when audio is loaded.
  • Updating presentTime whereas the audio performs, and resetting taking part in state when the audio ends.
useEffect(() => {
  if (base64adio) {
    const audio = new Audio(`information:audio/x-wav;base64, ${base64adio}`);
    setAudioFile(audio);

    audio.onloadeddata = () => {
      const audioDuration = audio.period;
      if (typeof audioDuration === "quantity" && !isNaN(audioDuration)) {
        setDuration(formatTime(audioDuration));
      }
    };
  }
}, [base64adio]);

6. Update present time whereas audio is taking part in

including the occasion to handle present time

useEffect(() => {
    if (audioFile) {
      // // Update present time whereas audio is taking part in
      audioFile.ontimeupdate = () => {
        const period = audioFile.period;
        const presentTime = audioFile.presentTime;
        if (period === presentTime) {
          isPlaying(false);
          audioFile.presentTime = 0;
          audioFile.pause();
          setCurrentTime(formatTime(audioFile.presentTime));
        } else {
          setCurrentTime(formatTime(presentTime));
        }
      };
    }

7. Rendering the Component

The part’s return operate contains:

  • presentTime and period show.
  • Icon buttons for skip again, play/pause, cease, and skip ahead. Each icon is styled and sized for a greater look and person interplay.
return (
  <div className="flex items-center justify-between mx-1">
    {presentTime}
    <IoPlaySkipBackCircleOutline onClick={deal withSkipBack} measurement={25} />
    {taking part in ? (
      <IoPauseCircleOutline onClick={deal withPlayPause} measurement={25} />
    ) : (
      <IoPlayCircleOutline onClick={deal withPlayPause} measurement={25} />
    )}
    <IoStopCircleOutline onClick={deal withStop} measurement={25} />
    <IoPlaySkipForwardCircleOutline onClick={deal withSkipForward} measurement={25} />
    {period}
  </div>
);

Usage Example

To combine this audio participant in your undertaking, you solely must move the audio information in base64 format to the any part. The participant will deal with playback controls seamlessly, offering an easy-to-use audio expertise.

Complete code

Here is the entire working code.


import React, { useEffect, useState } from "react";
import {
  IoPlayCircleOutline,
  IoPauseCircleOutline,
  IoStopCircleOutline,
  IoPlaySkipBackCircleOutline,
  IoPlaySkipForwardCircleOutline,
} from "react-icons/io5";

const PlayStory = (props) => {
  const { base64adio } = props;
  const [playing, isPlaying] = useState(false);
  const [audioFile, setAudioFile] = useState(null);
  const [duration, setDuration] = useState("00:00");
  const [currentTime, setCurrentTime] = useState("00:00");

  const deal withStop = () => {
    audioFile.pause();
    audioFile.presentTime = 0;
    isPlaying(false);
  };

  const deal withSkipBack = () => {
    const newTime = audioFile.presentTime - 10;
    audioFile.presentTime = newTime < 0 ? 0 : newTime;
  };

  const deal withSkipForward = () => {
    const newTime = audioFile.presentTime + 10;
    audioFile.presentTime =
      newTime > audioFile.period ? audioFile.period : newTime;
  };

  const deal withPlayPause = () => {
    if (audioFile) {
      if (taking part in) {
        audioFile.pause();
      } else {
        audioFile.play();
      }
      isPlaying((pre) => !pre);
    }
  };

  useEffect(() => {
    if (base64adio) {
      const audio = new Audio(`information:audio/x-wav;base64, ${base64adio}`);
      setAudioFile(audio);

      audio.onloadeddata = () => {
        const audioDuration = audio.period;
        if (typeof audioDuration === "quantity" && !isNaN(audioDuration)) {
          setDuration(formatTime(audioDuration));
        }
      };
    }
  }, [base64adio]);

  useEffect(() => {
    if (audioFile) {
      // // Update present time whereas audio is taking part in
      audioFile.ontimeupdate = () => {
        const period = audioFile.period;
        const presentTime = audioFile.presentTime;
        if (period === presentTime) {
          isPlaying(false);
          audioFile.presentTime = 0;
          audioFile.pause();
          setCurrentTime(formatTime(audioFile.presentTime));
        } else {
          setCurrentTime(formatTime(presentTime));
        }
      };
    }

    return () => {
      if (audioFile) {
        audioFile.onloadeddata = null; // Cleanup on unmount
        audioFile.ontimeupdate = null; // Cleanup on unmount
      }
    };
  }, [audioFile]);

  return (
    <div className="flex items-center justify-between mx-1">
      {presentTime}
      <IoPlaySkipBackCircleOutline
        className="cursor-pointer text-gray-800 size-6"
        measurement={25}
        onClick={deal withSkipBack}
      />
      {taking part in ? (
        <IoPauseCircleOutline
          onClick={deal withPlayPause}
          className="cursor-pointer text-gray-800 size-6"
          measurement={25}
        />
      ) : (
        <IoPlayCircleOutline
          onClick={deal withPlayPause}
          className="cursor-pointer text-gray-800 size-6"
          measurement={25}
        />
      )}
      <IoStopCircleOutline
        className="cursor-pointer text-gray-800 size-6"
        measurement={25}
        onClick={() => deal withStop()}
      />
      <IoPlaySkipForwardCircleOutline
        className="cursor-pointer text-gray-800 size-6"
        measurement={25}
        onClick={deal withSkipForward}
      />
      {period}
    </div>
  );
};

export default PlayStory;

const formatTime = (seconds) => {
  const minutes = Math.flooring(seconds / 60);
  const remainingSeconds = Math.flooring(seconds % 60);
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
    .toString()
    .padStart(2, "0")}`;
};

Conclusion

This audio participant part gives an effective way to combine audio playback controls in React purposes. With customizable controls and a transparent visible structure, it’s straightforward so as to add, modify, or increase its functionalities.

HI-FI News

through DEV Community: react https://dev.to/t/react

November 7, 2024 at 10:22AM