Implementing audio in React Websites
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.
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:
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.
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.)
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.
const [playSound] = useSound(clickSound, {
volume: 0.5,
});
Controlling the Pitch
You can also control the pitch/speed of the sound using the playbackRate
option.
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.
const [playSound] = useSound(clickSound, {
volume: 0.5,
playbackRate: 1.5,
interrupt: false
});
This will be the result:
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:
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:
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.
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.
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:
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!