Categories
React Answers

How to Play an MP3 Clip on Click in React?

Spread the love

Sometimes, we want to play an mp3 clip on click in React.

In this article, we’ll look at how to play an mp3 clip on click in React.

Play an MP3 Clip on Click in React

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL.

Then we call play on the created object to play the audio clip.

For instance, we write:

import React from "react";

export default function App() {
  const audio = new Audio(
    "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
  );

  const start = () => {
    audio.play();
  };

  return (
    <div>
      <button onClick={start}>Play</button>
    </div>
  );
}

We create the audio object with the Audio constructor with the MP3 file URL as its argument.

Then we call audio.play in the start function to play the audio clip when we click Play since we set start as the value of the onClick prop as the button.

Conclusion

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL.

Then we call play on the created object to play the audio clip.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Play an MP3 Clip on Click in React?”

How can I make the button reusable If I have 5 buttons in the page to play different mp3s? Also pls add how to stop a sound playing. Thank you

Leave a Reply

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