To play a notification sound in React, you can use the use-sound library. Install the library, then import useSound in your React component and pass the sound file (e.g., notification.mp3) as an argument. Create a playSound function from useSound and attach it to an event, such as a button click or a specific app event, to play the notification sound.
How to play sound in React
Key takeaways:
The
use-soundlibrary simplifies adding sound to React components, offering a straightforward way to integrate interactive audio features.Install the
use-soundpackage via npm to enable audio playback in your React project.Use the
useSoundhook to load an audio file and play it using an event handler, like a button click.The library can be used to implement features like immersive sound effects, hover interactions, and dynamic pitch control in various web applications.
In React applications, incorporating sound effects enhances the user experience by providing audio feedback for successful actions, errors, or important events. The use-sound library simplifies sound integration within React components, making it easier to create more engaging and interactive web applications.
This Answer covers how to add sound effects in React using React’s use-sound library, including playing sounds on button clicks, hover sounds, and controlling pitch and volume for an immersive user experience.
Steps to play sound in React
Let's implement the solution by setting up a React application and installing the required dependencies.
Step 1: Installing dependencies for React sound effects
To get started with adding sound effects in React, we’ll need to install the use-sound package using npm. Before proceeding, ensure your React application is already set up.
If you need to create a new React application, follow these steps:
npx create-react-app soundReactcd soundReact
Then, navigate to the root directory of your project (in this case,
soundReact) and installuse-soundwith the following command:
npm i use-sound
This command will add use-sound to your project’s dependencies, allowing you to use it to play sounds in React.
Note: If you want to learn more about how to create a React application, look into this: How to create a simple app using React
Step 2: Playing audio using use-sound in React
The use-sound library makes it simple to add sounds to React components. Here’s an example of how to play a sound in React when clicking a button.
import React from 'react';import useSound from 'use-sound';const App = () => {const [playSound] = useSound('sound.mp3');return (<div><button onClick={playSound}>Play Sound</button></div>);};export default App;
The code snippet shows a simple sound player implemented in a React functional component using the use-sound library.
Line 2: We import
useSoundhook from theuse-soundlibrary.Line 5: The
useSoundhook accepts an audio file path (sound.mp3in this case) as an argument and returns a function,playSound, which plays the sound when invoked.Line 9: Assigning
playSoundto theonClickevent handler of the button ensures that clicking the button will play the audio file.
This straightforward implementation enables developers to integrate sound effects or audio playback into their React applications, making it an ideal solution for adding interactive and engaging features to web projects.
Step 3: Playing sound in the React application
We can make use of the use-sound package for various functionalities in our application. Let's begin with a simple illustration demonstrating how to play a sound in React. In this instance, we'll observe how to trigger a sound when clicking a button.
import React from 'react';
import useSound from 'use-sound';
import blast from './blast.mp3';
const SoundEffect = () => {
const [playSound] = useSound(blast);
// CSS styles for the button
const buttonStyles = {
padding: '12px 24px',
fontSize: '18px',
background: '#007BFF',
color: '#fff',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
outline: 'none',
boxShadow: '0px 2px 5px rgba(0, 0, 0, 0.2)',
transition: 'background-color 0.2s, transform 0.2s',
};
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<button
onClick={playSound}
style={{ ...buttonStyles }}
onMouseEnter={() => {
document.body.style.cursor = 'pointer';
}}
onMouseLeave={() => {
document.body.style.cursor = 'auto';
}}
>
💣Play Sound💣
</button>
</div>
);
};
export default SoundEffect;
Code explanation
In the above App.js file:
Line 6: It uses the
useSoundhook from theuse-soundlibrary to play a sound when a button is clicked. Theblast.mp3audio file is imported and passed as an argument to theuseSoundhook, which returns aplaySoundfunctionLine 25: When the button is clicked, the
playSoundfunction is called triggering the audio playback.
Additional functionalities with use-sound in React
The use-sound library offers additional features beyond basic React audio playback. Here are some ways to use these functionalities:
Triggering sounds on events in React:
use-soundcan be used to play sounds on specific user actions, like button clicks or form submissions, adding a layer of audio feedback.Adding hover sound effects in React: The library allows you to play sounds when the user hovers over certain elements, like buttons or images, adding an interactive auditory experience.
Note: If you want to learn more about how to play sound when hovering over a button, look into this: How to play sound when hovering in React.
React checkbox sound effects: Adding sound to checkboxes can enhance the user experience by providing audio feedback when boxes are checked or unchecked.
Note: If you want to learn more about how to play sound when using a checkbox, look into this: How to play sound with checkbox in React.
Pitch and playback rate control in sound: You can adjust the pitch and playback rate to create unique audio effects, like increasing speed for emphasis.
Note: If you want to learn more about how to increase pitch of a sound in React application, look into this: How to change pitch of a sound in React.
Volume and playback control: You can control the volume and playback of the sounds easily using the provided functions in the library.
Knowledge test
Let’s attempt a short quiz to assess your understanding.
What is not a feature provided by the use-sound library in React?
Triggering sound effects on button clicks or hover events
Controlling audio pitch, playback rate, and volume
Integrating background music with continuous looping
Conclusion
Using the use-sound hook in React is a straightforward way to integrate sound effects and play audio in React web applications. With customizable options such as pitch, playback rate, and volume control, it provides the flexibility to tailor audio feedback to different scenarios, from form submissions to button clicks and hover interactions.
Experimenting with use-sound features in React allows us to create a polished and immersive audio experience, adding a professional touch to our project and making it more engaging for users.
If you want to explore more about React, check out the What is React? A tutorial on how to get started blog on Educative platform.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
How to play notification sound in React?
How to use useSound in React?
How to record audio in React?
How do I create a custom audio player in React?
Free Resources