Categories
React Answers

How to Play Sound in React?

Spread the love

Sometimes, we want to play sound in React.

In this article, we’ll look at how to play sound in React.

Play Sound in React

To play sound in React, we can use the Audio constructor to create an audio element to play the clip.

Then we can control it with JavaScript.

For instance, we can write:

import React, { useEffect, useState } from "react";

const useAudio = (url) => {
  const  = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

const toggle = () => setPlaying(!playing);

  useEffect(() => {
    playing ? audio.play() : audio.pause();
  }, [playing, audio]);

  useEffect(() => {
    audio.addEventListener("ended", () => setPlaying(false));
    return () => {
      audio.removeEventListener("ended", () => setPlaying(false));
    };
  }, );

  return [playing, toggle];
};

export default function App() {
  const [playing, toggle] = useAudio(
    "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
  );

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
}

We create the useAudio hook that takes the url of the clip that we want to play.

Then we create the audio state that’s set to the audio element that’s created with the Audio constructor with the url of the clip.

Then we create the playing state which keeps track of whether the audio clip is playing.

Next, we call the useEffect hook to call audio.play or audio.pause depending if playing is true or not.

After that, we call useEffect again with a callback to listen to the ended event and call setPlaying with false to set playing to false in either case.

Finally, we return playing and toggle so we can use them in a component.

In App , we call useAudio with the URL of the clip we want to play.

And then we set toggle as the value of onClick and display ‘Pause’ or ‘Play’ depending on the value of playing .

Now when we click on the button, the clip should play if it’s not playing and pause it otherwise.

Conclusion

To play sound in React, we can use the Audio constructor to create an audio element to play the clip.

Then we can control it with JavaScript.

By John Au-Yeung

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

One reply on “How to Play Sound in React?”

Looks like you are missing a critical variable here. Can you fill this in? Right after const

const useAudio = (url) => {
const MISSING = useState(new Audio(url));
const [playing, setPlaying] = useState(false);

Leave a Reply

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