How to Play Audio File on Button Click in React 18

Last Updated on by in React JS

React has gained significant popularity in the world of web development due to its dynamic architecture. When it comes to integrating audio functionality, specifically playing MP3 music files on a click event in React, there are many approaches to achieve this seamlessly.

In this short and sweet guide, we will teach you how to play audio files on button click in the React application using the HTML5 Audio tag.

The audio tag is used to embed sound content in web applications and HTML documents. It may contain one or more audio sources, playing music from an audio file using the src attribute. Integrating MP3 music file playback on click in a React application enhances user engagement and enriches the overall user experience.

Let’s embark on a journey to play audio clips on a button click in React.

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

How to Play MP3 Music File On Click in React Js

Conclusion

Adding sounds to web projects make them more engaging, allowing site visitors to listen to their choice of music, podcasts, and much more. You can add custom sound effects to your application, and adding personalized sound effects or music clips guarantees unique and realistic user experiences.

In this tutorial, we have learned How to play audio with the help of external MP3 file url using the click event handler, and audio tag in React without using any library or package.

Check out MDN web docs to know more about HTML5 audio tag.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.