How to Play MP3 Music File On Click in React Js
In this simple guide, we will learn how to play MP3 music file on button click in React js using bootstrap and functional component.
MP3 is a compressed digital audio file; it is generally used for podcast and transferring music. An MP3 format reduces the file size using the compression algorithm.
Sometimes, in our React application we have to add the sound effect, or some kind of music. While developing an application we may meet with peculiar requirements.
We have conjugated certain steps which will show you how to easily play a MP3 sound file in React js through the function component.
Install React App
To create the React project, you need to install it using the create-react-app tool.
You have to type the given command on the terminal screen; you may change app name if you want.
npx create-react-app my-react-app
Now, you have to get inside the app folder.
cd my-react-app
Install Bootstrap Library
To design the button which will invoke the music from the audio file we may use bootstrap css framework.
If you can write custom CSS then this package is not mandatory.
npm i bootstrap --legacy-peer-deps
Create Component File
Next, create the new folder by the name of components/, afterwards make the new file and name it UserProfile.js file.
Here is how a basic function component looks in React.
import React from 'react'
function UserProfile() {
return (
<div></div>
)
}
export default UserProfile
Play MP3 Music File
The initAudio() method gets the access to the button DOM element.
Use the audio tag followed by source, you can pass the file source path in the src tag.
Add the code in the components/UserProfile.js file.
import React from "react";
function UserProfile() {
let initAudio = () => {
const targetAudio = document.getElementsByClassName("audioBtn")[0];
targetAudio.play();
};
return (
<div>
<button className="btn btn-danger" onClick={initAudio}>
Play Mp3 Audio
</button>
<audio className="audioBtn">
<source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"></source>
</audio>
</div>
);
}
export default UserProfile;
Update App.js File
In this step, we will open the App.js file, this file is the main entry point of React.
We have to register the component inside the App() method.
import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import UserProfile from "./components/UserProfile";
function App() {
return (
<div className="container mt-3">
<h2 className="mb-3">React Play Mp3 Audio File Example</h2>
<UserProfile />
</div>
);
}
export default App;
View App in Browser
Lastly, type and invoke the given command to start the React application.
npm start
Here is the url which will run your app on the browser.
http://localhost:3000
Conclusion
In this tutorial, I have taught you how to create a button that plays a MP3 music file on button toggle or on click in React js without using any external library.