Audio player in React with example
Today we’ll show you how to implement an audio player in React with example. We had written an article to Embed YouTube video in ReactJS and also show you How to play an mp3 file in ReactJS.
In this article, we will create a simple example to add audio player in ReactJS using npm package.
Steps to add audio player in React
1. Create react application
Let’s create a react application using the create-react-app
npm package. Refer to the following link for the step by step explanation of the create react application.
Run the following command to create a react application.
1 | npx create-react-app audio-player-react-example |
2. Install npm package dependency
Now in the next step, we will use the react-player npm package to load the audio file in player. Run the following command to install the package.
1 | npm install react-player |
3. Add audio player in react component
So we will add the audio player by importing the react-player
package. Your code should look like this.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import React from 'react'; import ReactPlayer from "react-player"; function App() { return ( <div> <h3>Audio player in React - <a href="https://www.cluemediator.com">Clue Mediator</a></h3> <ReactPlayer url="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" width="400px" height="50px" playing={false} controls={true} /> </div> ); } export default App; |
In the above code, you have to pass the full path of the mp3 file in url
property. There are multiple options available to play with the audio player like playing, loop, controls, volume, etc.
The same package we can use as a video player. So it would be good to use this single package for implementation of both players.
4. Output
Run the project and check the output.
That’s it for today.
Thank you for reading. Happy Coding..!!