Adding Sound in Your App

Ronan McClorey
2 min readNov 8, 2020

--

While creating an app for children, I wanted to incorporate some interactive sounds to make it more appealing and fun. I was able to add different clickable sound effects, the apps frontend was made on React so here is one way of doing this!

Photo by Scott Major on Unsplash

To add clickable sound effects into your React app, you can first create a new react component. Since the sound effects, in this case, are clickable make this component a class component so that you can set the default state of ‘play’ to false and toggle the sound on and off. You can download sound files or use a sound file you already have, import the sound into the js file for this component, then inside the class create the audio component and assign it to an appropriate variable name (example of a sound effect of a dog barking):

audioDog = new Audio(dog)

In this example ‘dog’ is the imported audio file. Then we can create a toggle function to toggle the state of ‘play’ from true to false. If the state is true we can call the play function on the audio file and if it is false we can call the pause function on the audio file. Play() and pause() are built in functions we can call on audio files.

togglePlayDog = () => {
this.setState({ play: !this.state.play }, () => {
this.state.play ? this.audioDog.play() : this.audioDog.pause();
});
}

With this when the togglePlayDog function is called it will change the state from true to false or vice versa. Then the function will either call play() or pause() on the audio file depending based on whether the state is true or false because of the ternary statement.

Lastly to make this work you have you have to call the created ‘togglePlayDog’ function. One simple way to achieve this is by placing a click listener on the page you can place it wherever you like for example an image or a gif. For this example of code I will put a click listener on a gif of a barking dog.

<img scr="/dog-bark.gif" alt="dog" onClick={this.togglePlayDog} />
Photo by Devon Janse van Rensburg on Unsplash

With that by clicking on the gif you can play and pause your audio file!

The MDN docs explain using the audio constructor: https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio

--

--

No responses yet