playbackRate in the use-sound library controls the speed and pitch of the sound. Setting a higher playbackRate makes the sound play faster and at a higher pitch, while a lower playbackRate makes it slower and lowers the pitch.
How to change pitch of a sound in React
Key takeaways:
The
playbackRateparameter in theuse-soundlibrary allows developers to adjust the pitch of sounds in React applications.Higher playback rates increase pitch, while lower rates decrease it. Adjusting
playbackRatewithin the range of 0.5 to 3.0 ensures optimal sound quality and avoids distortion.Developers can create interactive controls, such as buttons to increase or decrease pitch, for a more engaging audio experience.
Changing pitch dynamically adds variety and makes sound interactions more engaging, immersive, and lively for users.
In React, you can change the pitch of a sound using the use-sound library by adjusting the playbackRate parameter. By setting a higher value for a playbackRate, the sound will play at a faster pace, effectively raising its pitch. Similarly, setting a lower playbackRate will make the sound play at a slower pace, lowering its pitch.
Changing pitch adds variety and liveliness to the audio experience within React applications. By manipulating pitch, developers can create unique tones, making sound interactions in React more engaging and immersive for users.
Steps to change pitch in React
Let's implement the solution by setting up a React application and installing the required dependencies.
Step 1: Installing the use-sound library in React
We'll need to install the use-sound library using npm, so make sure that our React application is built before we proceed.
Note: If you want to learn more about how to create a React application, then check this Answer: How to create a simple app using React.
Navigate to the root directory of the React project and install the use-sound library using the following commands.
cd soundReactnpm i use-sound
Step 2: Changing pitch using the use-sound library
Let’s walk through a basic example of how to change sound pitch in React. By using the playbackRate parameter, we can adjust the playback rate to increase or decrease the pitch of a sound dynamically in a React application.
import React from 'react';import { useSound } from 'use-sound';import audioTrack from '/path/to/your/sound.mp3'const App = () => {const soundUrl = audioTrackconst [play] = useSound(soundUrl, { playbackRate: 1.0 });const increasePitch = () => {// Increase pitch by 0.1 (10%)const newPlaybackRate = Math.min(2.0, play.playbackRate + 0.1);play({ playbackRate: newPlaybackRate });};const decreasePitch = () => {// Decrease pitch by 0.1 (10%)const newPlaybackRate = Math.max(0.5, play.playbackRate - 0.1);play({ playbackRate: newPlaybackRate });};return (<div><button onClick={increasePitch}>Increase Pitch</button><button onClick={decreasePitch}>Decrease Pitch</button></div>);};export default App;
In the above code:
Line 6: The
useSoundHook takes the sound URL and an options object as parameters. Here, we set the initialplaybackRateto1.0, which represents the default pitch.Lines 8–18: The functions
increasePitchanddecreasePitchmodify theplaybackRatestate variable.increasePitchraises theplaybackRateby0.1(10%) up to a maximum of2.0, whiledecreasePitchlowers it by0.1(10%) down to a minimum of0.5. This keeps the pitch within a reasonable range to avoid significant distortion.
Step 3: Adding interactive pitch controls in a React application
The example shows buttons to increase and decrease the pitch, creating an interactive and engaging audio experience for users within React applications.
import React, { useState } from 'react';
import useSound from 'use-sound';
import soapBubbles from './soap-bubbles-pop.mp3';
const SoundEffect = () => {
const soundUrl = soapBubbles;
const [playbackRate, setPlaybackRate] = useState(0.75);
const [isIncreaseButtonHovered, setIsIncreaseButtonHovered] = useState(false);
const [isDecreaseButtonHovered, setIsDecreaseButtonHovered] = useState(false);
const [play] = useSound(soundUrl, {
playbackRate,
});
const increasePitch = () => {
setPlaybackRate((prevRate) => Math.min(3.0, prevRate + 0.1));
play();
};
const decreasePitch = () => {
setPlaybackRate((prevRate) => Math.max(0.5, prevRate - 0.1));
play();
};
// CSS styles for the buttons
const buttonStyles = {
padding: '15px',
fontSize: '24px',
background: 'transparent',
border: '2px solid #007BFF',
borderRadius: '5px',
color: '#007BFF',
fontWeight: 'bold',
cursor: 'pointer',
outline: 'none',
transition: 'background-color 0.2s, color 0.2s', // Add transition for smooth color change
};
// Styles for the buttons when hovered
const buttonHoverStyles = {
background: '#007BFF',
color: '#fff',
};
// CSS styles for the button container
const buttonContainerStyles = {
display: 'flex',
gap: '20px', // Add a big margin between the buttons
margin: '40px 0', // Add a big margin above and below the button container
};
return (
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
}}
>
<div style={buttonContainerStyles}>
<button
onClick={increasePitch}
style={{ ...buttonStyles, ...(isIncreaseButtonHovered ? buttonHoverStyles : {}) }}
onMouseEnter={() => setIsIncreaseButtonHovered(true)}
onMouseLeave={() => setIsIncreaseButtonHovered(false)}
>
⬆️ Increase pitch ⬆️
</button>
<button
onClick={decreasePitch}
style={{ ...buttonStyles, ...(isDecreaseButtonHovered ? buttonHoverStyles : {}) }}
onMouseEnter={() => setIsDecreaseButtonHovered(true)}
onMouseLeave={() => setIsDecreaseButtonHovered(false)}
>
⬇️ Decrease pitch ⬇️
</button>
</div>
<p style={{ fontSize: '18px', marginTop: '10px' }}>
Pitch: {playbackRate.toFixed(2)}
</p>
</div>
);
};
export default SoundEffect;
In the above App.js file:
Lines 15–18: The
increasePitchfunction triggers when the “Increase Pitch” button is clicked.Line 16: It uses the
setPlaybackRatefunction, which is provided by theuseStateHook, to update theplaybackRatestate variable by adding0.1, keeping it below the maximum value of3.0.
Lines 20–23: The
decreasePitchfunction is triggered when the “Decrease Pitch” button is clicked. It also uses thesetPlaybackRatefunction to update theplaybackRatestate variable by reducingplaybackRateby0.1but not going below0.5.
In both cases, the play function is called after the setPlaybackRate to ensure that the sound is played immediately with the newly adjusted pitch. The pitch value is updated in real time, and users can hear the sound at different pitches by clicking the respective buttons.
Note: Extreme values beyond
0.5to3.0may distort sound quality, so keepingplaybackRatewithin this range ensures the best audio experience in React applications.
Knowledge test
Let’s attempt a short quiz to assess your understanding.
In a React application, which parameter in the use-sound library is used to adjust the pitch of a sound?
volumeControl
playbackRate
soundPitch
audioFrequency
Conclusion
Using dynamic pitch control in React with the use-sound library enhances user interactions and the audio experience in React applications. Users can actively engage with sound elements, exploring various auditory effects in React.
Note: If you want to learn more about how to play sound in React, then check this Answer: How to play sound in React.
If you’re looking to dive deeper into React, consider reading our detailed blog, “React hooks design patterns and creating components without class.” This guide covers essential concepts like functional components and hooks, which are fundamental for building efficient and modern React applications. Gaining this foundational knowledge will enhance your skills and set you up for greater success as a front-end developer.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is playbackRate in React’s use-sound library?
What is the best way to add interactive sound effects in React?
Can we create dynamic audio effects in React with use-sound?
Free Resources