Often, We see some tiny little sounds that play on mobile apps. Remember that sound when you like a Facebook post? Many people are addicted to few app sounds and like posts just to listen to that sound.
Sounds do play a prominent role in making the user experience better by giving feedback on app actions. I always use sounds on my apps and most of them are built using React Native. So I’m writing this post to explain how to play app sounds in React Native
React Native Sound
React Native doesn’t have built-in support for playing in-app sounds so I’m using a library called react-native-sound – https://github.com/zmxv/react-native-sound
Check out the library using the above link. It contains the installation process and examples. I’ve also made a demo video on playing app sounds. Check out the demo video below.
Usage
If you check the library’s repo then you can find an example which is as follows
var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
// loaded successfully
console.log('duration in seconds: ' + whoosh.getDuration() + 'number of channels: ' + whoosh.getNumberOfChannels());
// Play the sound with an onEnd callback
whoosh.play((success) => {
if (success) {
console.log('successfully finished playing');
} else {
console.log('playback failed due to audio decoding errors');
}
});
});
This example won’t be helpful in a real-life app because this example shows how to load a sound and then play the sound after loading. The loading would cause delay and sound might not play instantly. Also, This would load the sound every time an action is made which is not the performant way to do.
Practical usage
Practically, We should preload the sound only once in the app initialization process and then reuse the same instance everywhere we need to play the sound. Here’s how it’s done :
- First, Save the sound clip file in the folder
android/app/src/main/res/raw
- Preload the sound in any of your root files
main.js
orapp.js
and export them. Here’s the code :
export var appSounds = {};
...
...
export default class Main extends Component {
componentDidMount() {
appSounds.likeSound = new Sound("like.mp3", Sound.MAIN_BUNDLE, error => {
if (error) {
console.log("failed to load the sound", error);
}
});
}
...
...
}
3. Import the file where you need to play the sound and play. Here’s the code :
import { appSounds } from '../main';
onButtonPress() {
appSounds.likeSound.play();
}
4. You can also add an if statement check to make sure that the app doesn’t crash if the sound hasn’t loaded due to corrupted file or any other reason.
onButtonPress() {
if (appSounds.likeSound) {
appSounds.likeSound.play();
}
}
That’s it 😉 Your sounds will play perfectly now. If you have any questions or feedback, Do let me know in the comments below 😍
Also, Do check out the other react native libraries that I use!