Introduction
If you're learning React and want to build a project, there are countless tutorials out there. However, one type of project that often gets overlooked is a music player. Building a music player is a fantastic way to learn how to handle audio in React, including playing, pausing, and managing audio timelines. In this tutorial, we’ll walk you through building a React music player step by step.
By the end of this tutorial, you’ll have a fully functional music player with the following features:
- Play and pause audio
- Display the current time and duration of the audio
- A draggable timeline to control playback
- Customizable UI with icons
Let’s dive in!
Prerequisites
Before we start, make sure you have the following:
- Basic knowledge of JavaScript, HTML/CSS, and React
- Node.js installed on your machine
Setting Up the Environment
To get started, create a new React project using the following command:
npx create-react-app react-music-player
Once the project is created, navigate to the project directory and remove any unnecessary boilerplate code. Now, let’s install the required dependencies.
Installing Dependencies
We’ll use two main libraries for this project:
- use-sound: A React hook for handling audio playback.
- react-icons: A library for adding icons to our player.
Install them using the following commands:
npm i use-sound react-icons
Building the Music Player
Step 1: Create the Player Component
Inside the src
folder, create a new directory called components
. Inside this folder, create a file named Player.js
. This component will handle all the logic and UI for our music player.
Step 2: Import Required Libraries
Start by importing the necessary libraries and assets:
import { useEffect, useState } from "react";
import useSound from "use-sound"; // For handling audio
import qala from "../assets/qala.mp3"; // Import your audio file
import { AiFillPlayCircle, AiFillPauseCircle } from "react-icons/ai"; // Play and pause icons
import { BiSkipNext, BiSkipPrevious } from "react-icons/bi"; // Next and previous icons
import { IconContext } from "react-icons"; // For customizing icons
Step 3: Set Up State and Audio Controls
Add the following state and logic to handle playing and pausing the audio:
const [isPlaying, setIsPlaying] = useState(false);
const [play, { pause, duration, sound }] = useSound(qala);
const playingButton = () => {
if (isPlaying) {
pause(); // Pause the audio
setIsPlaying(false);
} else {
play(); // Play the audio
setIsPlaying(true);
}
};
Step 4: Add the UI for the Player
Now, let’s add the UI for the music player:
return (
<div className="component">
<h2>Playing Now</h2>
<img className="musicCover" src="https://picsum.photos/200/200" alt="Album Cover" />
<div>
<h3 className="title">Rubaiyyan</h3>
<p className="subTitle">Qala</p>
</div>
<div>
<button className="playButton">
<IconContext.Provider value={{ size: "3em", color: "#27AE60" }}>
<BiSkipPrevious />
</IconContext.Provider>
</button>
{!isPlaying ? (
<button className="playButton" onClick={playingButton}>
<IconContext.Provider value={{ size: "3em", color: "#27AE60" }}>
<AiFillPlayCircle />
</IconContext.Provider>
</button>
) : (
<button className="playButton" onClick={playingButton}>
<IconContext.Provider value={{ size: "3em", color: "#27AE60" }}>
<AiFillPauseCircle />
</IconContext.Provider>
</button>
)}
<button className="playButton">
<IconContext.Provider value={{ size: "3em", color: "#27AE60" }}>
<BiSkipNext />
</IconContext.Provider>
</button>
</div>
</div>
);
Step 5: Add a Timeline for Audio Progress
To display the current time and duration of the audio, add the following code:
const [currTime, setCurrTime] = useState({ min: "", sec: "" });
const [seconds, setSeconds] = useState();
useEffect(() => {
const sec = duration / 1000;
const min = Math.floor(sec / 60);
const secRemain = Math.floor(sec % 60);
setCurrTime({ min, sec: secRemain });
}, [duration]);
useEffect(() => {
const interval = setInterval(() => {
if (sound) {
setSeconds(sound.seek([]));
const min = Math.floor(sound.seek([]) / 60);
const sec = Math.floor(sound.seek([]) % 60);
setCurrTime({ min, sec });
}
}, 1000);
return () => clearInterval(interval);
}, [sound]);
Add the timeline UI to the return statement:
<div>
<div className="time">
<p>{currTime.min}:{currTime.sec}</p>
<p>{time.min}:{time.sec}</p>
</div>
<input
type="range"
min="0"
max={duration / 1000}
value={seconds}
className="timeline"
onChange={(e) => sound.seek([e.target.value])}
/>
</div>
Styling the Player
Add the following CSS to style your music player:
body {
background-color: #e5e5e5;
}
.App {
font-family: sans-serif;
text-align: center;
}
.component {
background-color: white;
width: 25%;
max-width: 600px;
margin: 1em auto;
padding-bottom: 2em;
border: 0.1px solid black;
border-radius: 10px;
}
.musicCover {
border-radius: 10%;
}
.playButton {
background: none;
border: none;
align-items: center;
justify-content: center;
}
.subTitle {
margin-top: -1em;
color: #4f4f4f;
}
.time {
margin: 0 auto;
width: 80%;
display: flex;
justify-content: space-between;
color: #828282;
font-size: smaller;
}
.timeline {
width: 80%;
background-color: #27ae60;
}
input[type="range"] {
background-color: #27ae60;
}
@media (max-width: 900px) {
.component {
width: 50%;
}
}
Output
After completing the project, your music player will look like this:
Additional Features
You can extend this project by adding features like:
- A playlist to play multiple songs
- Volume control
- Shuffle and repeat functionality
- Custom animations and transitions
Conclusion
Congratulations! You’ve built a fully functional music player in React. This project is a great way to learn how to handle audio in React and create interactive UIs. Feel free to customize and expand this project further.
If you found this tutorial helpful, let me know in the comments! And if you’d like to see a tutorial on building a video player in React, drop a comment below.
Happy coding! 🎧