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.
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
Thedeal withPlayPauseoperate toggles between taking part in and pausing the audio based mostly on thetaking part instate. When paused, it stops audio playback; when performed, it resumes. -
Stop
Thedeal withStopoperate stops the audio, unitspresentTimeto the start, and resets thetaking part instate. -
Skip Back/Forward
Thedeal withSkipBackanddeal withSkipForwardfeatures 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
periodwhen audio is loaded. - Updating
presentTimewhereas the audio performs, and resettingtaking part instate 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:
-
presentTimeandperiodshow. - Icon buttons for
skip again,play/pause,cease, andskip 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
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








