How to play an mp3 file in ReactJS

Today we’ll show you how to play an mp3 file in ReactJS. In this short article, we’ll create an example to play an mp3 sound file in React.js.

How to play an mp3 file in ReactJS, react onclick play audio, react import mp3, react-sound tutorial, react audio player ui npm, Adding mp3 files to a Create React App app, A simple MP3 player with React.js, audio player in React, How to play sounds in React JS, Playing a sound file in a React project.

Steps to play an mp3 file

  1. Setup a react application
  2. Create component to play sound
  3. Output

1. Setup a react application

First, we have to create an application in React JS. If you don’t know how to do it then refer to this link.

2. Create component to play sound

Here we’ll implement a demo in App.js file only. Let’s take three buttons for play, pause and stop audio sound. Also add a checkbox to set the loop of the audio tune based on the selection.

At the beginning of the demo, we will use Audio constructor using JavaScript to create HTMLAudioElement. Also declare variable to play audio in loop.

In the below code, update the audio file path of .mp3

Load audio file on componentDidMount.

Set loop to audio on checkbox change.

Create methods to play, pause and stop the audio sound.

Check the below HTML elements to create a demo.

That’s the changes required to play audio file. Let’s combine all together in one file.

App.js

3. Output

Run the project and check the output.

Output - How to play an mp3 file in ReactJS - Clue Mediator
Output – How to play an mp3 file in ReactJS – Clue Mediator

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

Demo & Source Code

Github Repository StackBlitz Project

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *