How to Play an MP3 Clip on Click in React?

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.