Implementing audio in React Websites
Published: 2023-06-08 01:25:01

by [Saleh Mubashar](https://blog.openreplay.com/authors/saleh-mubashar)

<blockquote><em>Keeping a user hooked to your website and making them spend as much time as possible is very important. A very useful, yet less talked about method to grab a user's attention, is sound. This article will discuss how to implement sound in a React website and how to use the `useSound` hook to add sound effects to React components.</em></blockquote>


Appropriate use of sound in web design is important. Audio effects should be used in moderation and not be annoying like those background popups back in the day.

One of the best ways to use sound on websites is through interactive responses. These include alerts and notifications in, for example, chat groups. Another use case is playing audio effects when users interact with UI elements such as buttons, checkboxes, etc.

Since sound is very rarely used on websites, it can be a great way to catch a user's attention if used correctly. 

## Getting Sound Effects

Before we move on to the use-sound hook and the actual implementation of sound effects, we need to get the audio files from somewhere. A few popular and free sites for sound effects include:

* [Freesound](https://freesound.org/)
* [Zapsplat](https://www.zapsplat.com/)
* [Mixkit](https://mixkit.co/free-sound-effects/)

For our examples, we shall use sounds from Freesound.

## The Use-Sound React Hoook

`use-sound` is a React hook that allows you to play sound effects when you interact with UI elements, for example. It has a bunch of cool features, which include:

- Control the Volume
- Control the pitch
- Change the playback rate
- Interrupts
- Play sound on different types of events
- Sprites

You can install it using `npm install use-sound` or `yarn add use-sound`.

In the next section, let's look at a few examples which use this hook.

## Button Click Effect

Let's start by creating a blank React App. In your App.js file, import the use-sound hook. We will create a simple HTML button and play a sound effect each time a user clicks on the button. For the sound effect, I am using a particular sound clip. We will save this mp3 in our src folder and import it into App.js.

```javascript
import "./styles.css";
import useSound from "use-sound";
import clickSound from "./button_click.mp3";

export default function App() {
  return (
    <div className="App">
      <button>Click Me!</button>
    </div>
  );
}
```

Next, we will create a variable called playSound. We will assign the `useSound` function to it. The name of the audio file will be given as a parameter to the `useSound` hook. This variable will be called `onClick` on the button. Make sure to wrap the variable name with square brackets to unpack (destructure) the property from the object (the result of calling the `useSound` hook.)

```javascript
import "./styles.css";
import useSound from "use-sound";
import clickSound from "./button_click.mp3";

export default function App() {
  const [playSound] = useSound(clickSound);
  return (
    <div className="App">
      <button onClick={playSound}>Click Me!</button>
    </div>
  );
}
```

### Controlling the Volume

We can customize the volume of the sound effect as well by passing the `useSound` hook to an object containing different options, which include volume. The value of `volume` is a number from 0 to 1.

```javascript
const [playSound] = useSound(clickSound, {
  volume: 0.5,
});
```

### Controlling the Pitch

You can also control the pitch/speed of the sound using the `playbackRate` option.

```javascript
const [playSound] = useSound(clickSound, {
  volume: 0.5,
  playbackRate: 1.5
});
```

### Interrupts

You can use the `interrupt` boolean property to specify whether or not a sound effect should overlap or play on top of an already running sound.

```javascript
const [playSound] = useSound(clickSound, {
  volume: 0.5,
  playbackRate: 1.5,
  interrupt: false
});
```


**This will be the result:**

<iframe src="https://codesandbox.io/embed/button-click-sound-effect-fo91hv?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark"
     style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
     title="Button Click Sound Effect"
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>
   
   
## Checkbox

In this example, we will use a state to check whether the user clicked the checkbox. This is so that we can play different types of sounds when the user checks it and when it is unchecked.

The basic implementation is similar to the example discussed above:

```javascript
import "./styles.css";
import useSound from "use-sound";
import { useState } from "react";

export default function App() {
  const [checked, setChecked] = useState(false);
  return (
    <div className="App">
      <input type="checkbox" onChange={() => setChecked(!checked)} />
      <label>Checked</label>
    </div>
  );
}
```

The checked state is toggled each time the checkbox is clicked. Now we will create two separate `useSound` functions using two separate audio files.
We will call these functions based on the checked state onMouseUp. I have tweaked the pitch and volume to fine-tune the effect.

The result will look this:

<iframe src="https://codesandbox.io/embed/check-box-sound-effect-foytn5?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark"
     style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
     title="Check Box Sound Effect "
     allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
     sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
   ></iframe>


<div style="background-color:#efefef; border-radius:8px; padding:10px; display:block;">
<hr/>
<h3><em>Session Replay for Developers</em></h3> 
<p><em>Uncover frustrations, understand bugs and fix slowdowns like never before with <strong><a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a></strong> — an open-source session replay suite for developers. It can be <strong>self-hosted</strong> in minutes, giving you complete control over your customer data.</em></p>
<img alt="OpenReplay" style="margin-top:5px; margin-bottom:5px;" width="768" height="400" src="https://raw.githubusercontent.com/openreplay/openreplay/main/static/openreplay-git-hero.svg" class="astro-UXNKDZ4E" loading="lazy" decoding="async">
<p><em>Happy debugging! <a href="https://openreplay.com" target="_blank">Try using OpenReplay today.</a></em><p>
<hr/>
</div>




## Sprites

If you are using multiple audio effects in your app, importing a single file rather than a different one for each sound is better. A sprite is a single audio file that contains many sound effects. We can choose specific parts of the video by providing the starting timestamp and the duration in milliseconds. 

```javascript
const [soundEffect] = useSound(soundFile, {
  sprite: {
    guitar: [0, 500],
    drum: [500, 200],
    piano: [700, 300],
    violin: [1000, 400],
  },
});
```

The sprite object contains individual information on each sound effect. To play it, we can choose a specific sound using its id like this:

```javascript
import "./styles.css";
import useSound from "use-sound";
import sounds from "./sounds.mp3";

export default function App() {
  const [soundEffect] = useSound(soundFile, {
    sprite: {
      guitar: [0, 500],
      drum: [500, 200],
      piano: [700, 300],
      violin: [1000, 400],
    },
  });
  return (
    <div className="App">
      <button onClick={() => soundEffect({id: 'guitar'})}>Click Me!</button>
    </div>
  );
}
```


## Conclusion

These are just some of the few possible implementations and examples of using sound on the web to improve user experience. 

By incorporating sound strategically in your website, you can create an immersive and engaging web experience. However, it's crucial to approach sound implementation with care and consideration for the user, ensuring that it enhances the experience rather than detracting from it.


Thanks for reading!