Clue Mediator

Audio player in React with example

📅September 13, 2020

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
  2. Install npm package dependency
  3. Add audio player in react component
  4. Output

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.

Create react application

Run the following command to create a react application.

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.

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

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>
    </reactplayer></div>
  );
}

export default App;

MP3 File Source

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.

Output - Audio player in React with example - Clue Mediator

Output - Audio player in React with example - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project