Playing Sound in React Native Apps using React-Native-Sound

Topics Covered

Overview

Using audio elements into your application is an effective strategy for engaging users. In this article, we explore the capabilities of this powerful audio component and how it can revolutionize your application's sound-related tasks. From adding delightful notification tones to implementing immersive audio effects, react-native-sound unlocks endless possibilities for creating a truly engaging user experience. Dive in and unleash the potential of sound in your React Native app!

What is React Native Sound?

The react-native-sound module is a widely used component in React Native that allows you to play sound clips on iOS, Android, and Windows platforms. It offers the capability to incorporate audio from various sources such as the app bundle, JavaScript bundle, or remote paths (local storage or remote URLs).

Unlike a class component, react-native-sound functions more like a class, providing predefined methods for controlling instances without the need to update states or props. This feature helps prevent slow rerenders of the app, addressing related concerns.

Despite its documentation cautioning about potential bugs due to its alpha quality, react-native-sound remains one of the most popular and extensively employed sound libraries for React Native today.

Features

The features of the react-native-sound library include: Audio Playback: The library provides the capability to play audio files in various formats, such as MP3, WAV, and AAC.

Local File Support: It allows you to play audio files stored locally on the device, enabling playback of pre-downloaded or bundled audio resources.

Volume Control: The library provides controls to adjust the volume of the audio playback, allowing users to set the desired sound level.

Playback Control: It offers essential playback controls like play, pause, stop, and seek, giving users the ability to control the audio playback as needed.

Looping: The library supports audio looping, allowing you to repeat audio files continuously for background music or other looping scenarios.

Audio Recording: It provides functionality to record audio using the device's microphone, enabling the development of apps that require audio recording capabilities.

Event Handling: The library offers event-based callbacks for various audio playback events, such as completion, errors, or interruptions, providing flexibility in handling different scenarios during playback.

Cross-Platform Support: React-native-sound is designed to work seamlessly across different platforms, including iOS and Android, ensuring consistent audio playback experiences across devices.

Customization Options: It offers configuration options for audio playback, such as setting audio quality, choosing audio output routes, and enabling background audio playback, allowing developers to customize the audio experience based on their requirements.

The React-native-sound library does not have streaming capabilities. When working with iOS, the AVAudioPlayer library is utilized instead of AVPlayer.

Here are the supported features across different platforms:

FeatureiOSAndroidWindows
Load sound from app bundleYesYesYes
Load sound from other directoriesYesYesYes
Load sound from networkYesYesNo
Play soundYesYesYes
Playback completion callbackYesYesYes
PauseYesYesYes
ResumeYesYesYes
StopYesYesYes
ResetNoNoYes
Release resourceYesYesYes
Get durationYesYesYes
Get number of channelsYes No No
Get/set volumeYesYesYes
Get system volumeYesYes
Set system volumeNoYesNo
Get/set panYesNoNo
Get/set loopsYesYesYes
Get/set current timeYesYesYes
Set speedYesYesNo

How to Use react-native-sound?

To use the react-native-sound library in your React Native project, Install the library in your project directory, run the following command to install react-native-sound via npm or yarn. For npm users:

For yarn users:

Setting Up React-Native-Sound

To utilize react-native-sound, it is necessary to have the desired sounds accessible in your app. If the sounds are not available remotely (i.e., they are located within the app's package rather than on the device's external storage or a remote server), you will need to add them.

For iOS, you need to manually configure the project. If you are using CocoaPods, open the iOS project by navigating to the ios directory and running:

For Android, the linking process should be automatically handled. If you encounter any issues, refer to the manual linking instructions provided in the react-native-sound documentation.

Once you have completed these steps, you should have react-native-sound successfully set up in your project and ready to use. You can now import and utilize the package in your code to play sounds in your React Native app.

How to Add Sound in React Native Apps?

Next, let's proceed with using the desired sounds in our app. This particular stage focuses on understanding the process of bundling audio files within the native package. Additionally, we will explore a more straightforward approach to accessing the audio files from the assets directory.

  • To accomplish this in Android, begin by creating the "mySounds" directory and then proceed to copy the sounds into it. {YourAwesomeApp}/android/app/src/main/res/mySounds

  • To add files to your iOS project in Xcode, follow these steps:

  1. Open the workspace in Xcode.
  2. Right-click on the project.
  3. Select "Add files to {project_name}" from the options menu.

Please note that these instructions are specific to iOS development in Xcode. Once the sound files have been added, proceed to build the application and run it on either a simulator or, ideally, an actual device.

How to Play Sound from a Bundle?

Playing sounds from a bundle using react-native-sound gives you the flexibility to include sound files directly within your application package, reducing dependencies on external resources. This is particularly useful for offline functionality or when you want to ensure consistent playback across different devices.

Once the application is running smoothly, the next step is to begin the coding process. The initial task involves importing the sound component into the application.

import Sound from 'react-native-sound';

Create a new instance of the Sound class and provide the filename of the sound file within the bundle:

The Sound.MAIN_BUNDLE parameter indicates that the sound file is located in the main bundle of your application.

To play the sound, call the play() method:

You can also pass a callback function to play() to handle success or failure events.

Optionally, you can handle pausing, stopping, or releasing the sound when necessary:

These methods allow you to control the playback of the sound as needed.

Ensure that the sound file you want to play is in the correct format supported by react-native-sound (e.g., MP3, WAV) and is located in the specified path within the bundle. Adjust the code accordingly if your sound file is in a different directory within the bundle.

Sound Files Import

To import sound files in react-native-sound, you need to place the sound files in the appropriate location within your project and specify the correct path when creating a new Sound instance. Here's how you can import sound files in react-native-sound:

  • Create a folder within your project directory to store the sound files. For example, you can create a folder called sounds at the root level of your project.
  • Copy or move the sound files you want to import into the sounds folder. Make sure the sound files have compatible formats like MP3 or WAV.
  • In your JavaScript file where you want to use the sound, import the react-native-sound module.
  • Use the appropriate path to refer to the sound file when creating a new Sound instance. Here's an example:

In the above code, sounds/soundfile.mp3 represents the relative path to the sound file within the sounds folder. Adjust the path and file name according to your folder structure and sound file name.

Using Remote Path to Play Sound

If you wish to play files from remote locations or local storage, it is straightforward to do so with react-native-sound. Simply provide the file's URL as the first parameter for the Sound component and set the second parameter to null since the file is sourced from remote or local storage, rather than within the app.

Create a new instance of the Sound class and provide the remote sound file's URL as the first parameter:

To play the sound, call the play method on the sound object:

Make sure to replace http://example.com/sound.mp3 with the actual URL of your remote sound file.

FAQs

Q. Are there any events or callbacks available for handling sound playback in react-native-sound?

A. Yes, react-native-sound offers several events and callbacks that you can utilize. These include the onPlay event, onPause event, onStop event, onEnd event, and onError event, among others. You can attach event listeners to the sound object to respond to these events accordingly.

Q. Can I play sound files from a remote URL using react-native-sound?

A. Yes, react-native-sound supports playing sound files from remote URLs. Simply provide the URL as the first parameter to the Sound component constructor. For example:

Q. Does react-native-sound support looping and adjusting the volume of a sound?

A. Yes, react-native-sound allows you to loop a sound using the setNumberOfLoops method, where you can specify the number of times the sound should repeat. Additionally, you can control the volume of a sound using the setVolume method, which accepts a value between 0.0 (silent) and 1.0 (maximum volume).

Conclusion

In conclusion, react-native-sound is a powerful audio library for React Native that enables developers to incorporate sound capabilities into their applications. By using react-native-sound, you can enhance user engagement by adding notification tones, immersive audio effects, and more. The library supports various features such as audio playback, volume control, playback control (play, pause, stop, seek), looping, and audio recording. It also provides event handling for different playback events and offers customization options for audio playback behavior.