Adding Sound to a React Project

Adding Sound to a React Project

·

3 min read

Adding Sounds to a react project is fairly simple. In this blog, I'll demonstrate how you can implement sound to your react project!

Prerequisites

  • Have NPM installed
  • Have Node installed
  • Familiarity with React and React hooks
  • Have an awesome React Project in mind (Perhaps a music portfolio site for a band you like)

1. Create your react project.

npx create-react-app sound-demo First start by creating your react project.

  • npx create-react-app sound-demo

2. Go to your App.js component in the src folder and delete the logo import and everything inside the div.

App.js

3. Add an NPM package called react-sound.

  • npm i react-sound or yarn add react-sound

Adding Background Music to your site

4. Import the song you would like to play and Sound from react-sound.

Importing Sound

5. Add the <Sound /> to your app with a few props:

  • url- Link to the music you imported
  • playStatus- We will set it to Sound.status.PLAYING.
  • playFromPosition- You could adjust the milliseconds of when the music should start playing, I would just leave it at 300.
  • onLoading- This is a prop that from the component,this gets called when the sound is loading, You can either add props to the your functional component or you can destructure your props. It would be assigned to handleSongLoading.
  • onPlaying- This gets called when the song is playing. It would be assigned to handleSongPlaying.
  • onFinishedPlaying- This function will get called when the song is finished playing. It would be assigned to handleSongFinishedPlaying.
  • (Optional) loop: you can set loop to either true or false. It would default to false.

6. Now if you run npm start or yarn start, your sound should be working!

Sound Component


Displaying a Button that Allows You to Play and Pause the Music

6. We should add a state to check whether the music should be playing or not.

  • First import useState from react
  • Then add our state which would be a boolean value, const [isPlaying, setIsPlaying] = useState(false);

7. Let's add a button

Sound Button

  • We'll set the onClick function to an anonymous function that's set the isPlaying state opposite to what the current state is.
  • Then for the text we'll add a ternary operator for if the state is false the text will display "Play", otherwise, it will display "Stop".

8. Set the playStatus of the <Sound /> component.

Sound Component

  • Set the playStatus to play only when isPlaying is set to true, otherwise, playStatus would be set to Sound.status.STOPPED.

And there you have it, you got a working sound component!

Completed Project