Dark Mode
Image

React Native Sound

Adding sounds to the app is a great way to engage the users. A small sound of a new notification, any "hiss type" sound of an email sent, or any crumbling sound of deleting files can create a better user experience for the React Native app.

We will explore react-native-sound, a powerful audio component that can easily handle sound-related tasks for our React Native app.

You have to be familiar with the basics of React Native, including the JSX, components, and styling.

React-native-sound is a module for playing sound clips on iOS, Android, and Windows. It allows us to add audio from various sources, Like (native) application packages, JavaScript packages, or remote paths (local storage or URL).

React-Native-Sound is a class component that helps to control instances by using predefined methods without updating states or props.

Although the documentation warns react-native-sound is "alpha quality and can contain bugs", it is the most popular used React Native sound library now.

Configuring react-native-sound (iOS and Android)

You will need the sounds you want to play in your app if they are unavailable remotely.

To add the react-native-sound to the app by using the package manager (for example, npm or yarn), enter the below command inside the app directory:

          $ yarn add react-sound-native  

If you are building, the linking is handled during the build process.

For iOS, we have to go to the iOS directory and call the pod install. It will add the capsule for react-native Sound.

Add Sounds to React Native App

Now, it's time to add the sounds that you want to play. We will look at an easier way to request audio files by the assets directory. For Android, we have to create a directory and then copy the sounds to it:

            {appDirectory}/android/app/src/main/res/raw  

For iOS, open the Workspace in Xcode, then click on the right on the project, then click Add Files to the {project_name}, as below:

React Native Sound
React Native Sound

The result looks something like this:

React Native Sound

After adding the sound files, we have to build the app and run it on the simulator on a real device.

After running it successfully, it is time to do the code part.

Firstly, we need to import the Sound into the application:

            import sound from 'react-native-sound';  

We're going to play, and we need to specify the range of the Sound before we can set the Sound:

            sound.setCategory('playback');  

Use the below code to start the sound:

var ding = new Sound('ding.mp3', sound.MAIN_BUNDLE, (error) => {  
  if (error) {  
    console.log('Failed to load the sound', error);  
    return;  
  }:  
  // loading it successfully  
   console.log('Duration in seconds: ' + whoosh.getDuration() + 'Number of the channels: ' + whoosh.getNumberOfChannels here());  
);  

The above code uses the first argument, ding.mp3, and a file from the bundle using the second argument, Sound.MAIN_BUNDLE, and returns a callback in the third argument.

\``getDuration is used for the duration of the audio file in seconds, and getNumberOfChannels is used to get the number of audio channels.

We can use the below method:

          ding.setVolume(1);  

Here, 1 is the highest volume, and 0 is the lowest. For example, to reduce the volume by 50 percent, you can set it to 0.5.

To play a file, we can use the sound-playing method as follows:

ding.play(success => {  
   if (success) {  
    console.log('audio playing ended successfully here');  
  } Otherwise {  
    console.log('Playback speed failed by audio decoding error');  
  );  
};  

The callback occurs in the payback is being completed.

To summarize the steps which are mentioned above:

  • Set the sound category to play
  • start the sound file
  • Adjust Volume, If it is Necessary
  • play the Sound

Below is the final code to play sound from the bundle:

import react from 'react', {useEffect};  
import {View, StyleSheet, TouchableOpacity} from 'react-native';  
import ionic from 'react-native-vector-icon/ionic';  
var sound = require('react-native-sound');  
sound.setCategory('playback');  
var ding = new Sound('ding.mp3', sound.MAIN_BUNDLE, (error) => {  
if (error) {  
    console.log('Failed to load sound', error);  
    return;  
 ) ;  
  // it loaded successfully here  
  console.log('Duration in seconds: ' + ding.getDuration() + 'Number of channels: ' + ding.getNumberOfChannels());  
);  
const app = () => {  
  use effect(() => {  
    ding.setVolume(1);  
    return () => {  
      ding.release();  
  );  
 } ;  
  cast play pause = () => {  
    ding.play(success => {  
      if (success) {  
        console.log('playing has been ended successfully');  
      } Otherwise {  
        console.log('Playback is failed by audio decoding error');  
     ) ;  
    },  
 },;  
  Return (  
    <view style={styles.container}>  
      <touchable opacity style={styles.playBtn} onPress={playPause}>  
        <ionic name={'ios-play-outline'} size={36} color={'#fff'} />  
      </touchableopacity>  
    </view>  
  );  
};  
const style = stylesheet. to create({  
  Container: {  
    Flex: 1;  
    align center',  
    justificationContent: 'center',  
    background color: '#000',  
 ) ;  
  playBTN: {  
    padding: 20;  
},  
export default App;  

Import Sound files

We use the same old requirement or import to get an instance of the file and convert it using react-native-sound.

Import the file -

import ding from './src/assets/ding.mp3';  
- and use in sound package:  
var ding = new Sound(dings, error => {  
  if (error) {  
    console.log('Failed to load sound', error);  
    return;  
 } ;  
  // if loaded the file successfully  
  console.log('Duration in seconds: ' + ding.getDuration() + 'Number of channels: ' + ding.getNumberOfChannels());  
};  

The difference when using a file imported from assets or required instead of bundled files is that you do not need to specify a base path for the file. Instead, the callback takes its place.

Below is the code for the component to play the imported file:

import react from 'react', {useEffect};  
import ding from './src/assets/ding.mp3';  
import {View, StyleSheet, TouchableOpacity} from 'react-native';  
import ionicon from 'react-native-vector-icon/ionic';  
var sound = require('react-native-sound');  
Sound.setCategory('playback');  
var ding = new Sound(dings, error => {  
  if (error) {  
    console.log('Failed to load the sound here', error);  
    return;  
  );  
  // loaded the sound successfully here  
  console.log(  
    'Duration in seconds:' +  
      ding.getDuration() +  
      'Number of channels:' +  
      ding.getNumberOfChannels(),  
 } ;  
);  
const app = () => {  
  use effect(() => {  
    ding.setVolume(1);  
    return () => {  
      ding.release();  
      
};  
  );  
  cast play pause = () => {  
    ding.play(success => {  
      if (success) {  
        console.log('Sound Playing ended successfully');  
      }   
Otherwise   
{  
        Console. Log ('Playback is failed by the audio decoding error');  
     ) ;  
   } ;  
 } ;  
  Return (  
    <view style={styles.container}>  
      <touchable opacity style={styles.playBtn} onPress={playPause}>  
        <ionic name={'ios-play-outline'} size={36} color={'#fff'} />  
      </touchableopacity>  
    </view>  
  );  
};  
Export default app;  

To play the sound, tap on the play button.

React Native Sound

Playing sound files from the remote path.

You have to play remote files from local storage. It is as simple as running the bundled file by using the react-native-sound.

You have to add the URL as the first parameter to the Sound and set the second parameter as null because the file is remote or local storage and not from the app.

var audio = new Sound(  
  'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3',  
  Zero,  
  error => {  
    if (error) {  
      console.log('Failed to load sound', error);  
      return;  
  ),  
    // if loaded successfully  
    console.log(  
      'Duration in seconds:' +  
        audio.getDuration() +  
        'Number of channels:' +  
        audio.getNumberOfChannels(),  
  } ;  
  );  
};  

Below is an example of playing, pausing, and releasing audio of the app which is closed or component is uncounted:

import react from 'react', { useEffect, useState};  
import {View, StyleSheet, TouchableOpacity} from 'react-native';  
import ionicon from 'react-native-vector-icon/ionic';  
var sound = require('react-native-sound');  
Sound.setCategory('playback');  
var audio = new Sound(  
  'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3',  
  Zero,  
  error => {  
    if (error) {  
      console.log('Failed to load the sound', error);  
      return;  
    };  
    // if loaded successfully  
    console.log(  
      'Duration in seconds:' +  
        audio.getDuration() +  
        'Number of channels:' +  
        audio.getNumberOfChannels(),  
   ) ;  
};  
  );  
};  
const app = () => {  
  const [playing, setPlaying] = useState();  
  use effect(() => {  
    audio.setVolume(1);  
    return () => {  
      audio.release();  
   ) ;  
 } ;  
  cast play pause = () => {  
    if (audio.isPlaying()) {  
      audio.pause();  
      setPlaying(false);  
    } Otherwise {  
      setPlaying(true);  
      audio.play(success => {  
        if (success) {  
          setPlaying(false);  
          console.log('audio play ended successfully');  
        } Otherwise {  
          setPlaying(false);  
          console.log('Playback is failed by audio decoding errors');          
);  
     } ;  
   ) ;  
 } ;  
  return (  
    <view style={styles.container}>  
      <touchable opacity style={styles.playBtn} onPress={playPause}>  
        < ionics  
          name = {playing? 'ios-pause-outline' : 'ios-play-outline'}  
          size = {36}  
          color = {'#fff'}  
       };  
      </touchable opacity>  
   ) ;  
View>  
 } ;  
),  
const style = stylesheet. to create({  
  Container: {  
    Flex: 1,  
    align center',  
    justificationContent: 'center',  
    background color: '#000',  
  );  
  playBTN: {  
    padding: 20,  
  },  
};  
export default App;  

.release() is used to release the memory for playing the audio clips.

It is important to release the memory when it is unmounted or cannot play the audio again. It helps to avoid memory leaks.

Feature Matrix

react-native-sound cannot support streaming. In iOS or Android, the library uses the AVAudioPlayer, not the AVPlayer.

Feature iOS Android Windows
load sound from the app bundle
Load sound from other directories
load sound from the network  
play sound
playback completion callback
prevent
resume
pause
reset    
release resource
get duration
Get the number of channels.    
get/set volume
get system volume  
set system volume    
Get/Set PAN    
get/set loop
get/set current time
Speed Set  

How to add Sound to a react-native app

If using React-Native 0.60 or higher, you will likely install the pod, but we will discuss it later.

The first thing we have to do is to open the command prompt/terminal and create a react-native project.

          react-native init mysoundproject  

After doing this, a project folder is created. Open the project in the favorite text editor, and then open the Terminal in a text editor. To open it on Mac, you must press "ctrl" and "`" together.

Enter Command

            npm install react-native-sound --save  

It will install React-Native Sounds, which allows you to play the sounds from a project or URL.

It would be best if you linked the dependencies. If you are using React-Native 0.60, you can run the below command:

cd ios && pod install

The directory changed to "ios" and started adding the dependencies.

You can use the below-given command if you are on a previous React-Native version.

             react-native link react-native-sound  

After you run the simulator on iOS by using the commands below;

                react-native run-ios react-native run-android  

src/main/res

React Native Sound

NOTE: The sound files we want to play will be lowercase and underscored if necessary.

Create another folder called "raw,"; which will contain your local sound file inside the res folder.

React Native Sound

We need to open your xcworkspace file in Xcode (if you're using react-native 0.60 or greater) If we want to play a sound file from your iOS simulator. Instead, open the xcodeproj file in the Xcode.

Right-click on the project name on the left and click "Add files to the project name".

React Native Sound

Look at the sound file on your hard drive, and "Copy items if necessary," and click "Add." Now you can see the sound file in the project.

React Native Sound

Now we have to import the package in the App.js file by using the below command.

           import sound from 'react-native-sound';  

Then we will create a " PlayLocalSoundFile " method and set the sound range to playback as we want a sound to be played.

PlayLocalSoundFile = () => {Sound.setCategory('Playback');}  

Now we have to run on the press of the first touchable opacity, so copy the code into the touchable opacity component.

            onPress={()=>this.PlayLocalSoundFile()}  

It look like below.

<touchable opacity style={  
{ background color: 'grey', justify content: 'center' }  
,  
onPress={()=>this.PlayLocalSoundFile()} >  
<text style=  
,  
{textAlign:'center',fontSize:20,color:'white',padding:10}  
,  
Play sound from local file</Text></TouchableOpacity>  

Play Sound from Remote URL

Playing a sound from a remote URL will be the same process, so go ahead and create a method called "PlayRemoteURLSoundFile". It will contain code to play the remote URL sound.

Now, set the category to playback like below because we want to play a sound, not a recording.

PlayRemoteURLSoundFile = () => { Sound.setCategory('Playback');  
};

We don't need to pass MAIN_BUNDLE Since we are not playing the sound file from the main bundle of the app;

Instead, we can pass in void, will be an error callback. The remote URL method will look like below code.

PlayRemoteURLSoundFile = () => { Sound.setCategory('Playback');  
var myRemoteSound = new Sound('https://www.soundjay.com/ambient/sounds/boarding-accouncement-1.mp3',null,(error)=>{  
if (error) { console. log(error);  
Return;  
};  
Otherwise  
);  
myRemoteSound.play((success)=>{if(success)  
},  
to console. log('playing sound')  
);  
else { console.log('Problem playing file'); } }) } }); myRemoteSound.setVolume(0.9);  
myRemoteSound.release();  
};    

Example Use Case

We have a column in the database table called "soundfilename," which is equal to the name of the sound file you want to play.

You can pull back the sound file name, put it in a method parameter, and put this parameter in the first participant for the "new sound" variable.

Conclusion

react-native-sound is a great module for adding a sound to the React Native app or creating any simple audio player.

If you want to explore more about it, we suggest trying Expo Unimodules' expo-av module to play the audio or video files in the React Native app.

Comment / Reply From