How to add sound to a react-native app

Alex
7 min readAug 5, 2020

--

Hi everyone, it has been a loooong time since I have written an article and thought I would do another today regarding adding sound to a react native app. Let’s go!

Firstly, the documentation for this can be found here — https://www.npmjs.com/package/react-native-sound and has a lot of great stuff in it, but if you like the format of Medium feel free to stick around!

I will be using React-Native 0.60 version or greater so you will most likely need to do a pod install but I will talk about that later.

The first thing you will want to do is to open your command prompt/terminal and create a react-native project, to do this enter the below.

Playing from local file

react-native init mysoundproject

After you have done this a project folder will be created, open this project in your favoured text editor, open the terminal within your text editor, to open this in vs code on a mac you will need to press “ctrl” and “`" at the same time.

Now enter the command

npm install react-native-sound --save

This will install the react-native-sound which is a fantastic package which allows you to play sounds locally from a project or from a url as well as a myriad of other features!

After that has installed you will need to link the dependencies, if you are using React-Native 0.60 you can run the below command

cd ios && pod install

This will change to the directory “ios” and begin to link the dependencies.

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

react-native link react-native-sound

After you have done run the simulator in either Android or iOS using either of the below commands

react-native run-iosreact-native run-android

This first run may take a while so be patient :)

I will show examples of both an audio file stored locally and a file from a remote url.

Firstly, remove the class or const “App” variable and replace it was the below. We are just creating a couple touchable areas on the screen to run our methods.

class App extends React.Component{render(){return(<View><View style={{marginTop:100}}><TouchableOpacity style={{backgroundColor:'grey',justifyContent:'center'}}><Text style={{textAlign:'center',fontSize:20,color:'white',padding:10}}>Play sound from local file</Text></TouchableOpacity></View><View style={{marginTop:100}}><TouchableOpacity style={{backgroundColor:'grey',justifyContent:'center'}}><Text style={{textAlign:'center',fontSize:20,color:'white',padding:10}}>Play sound from remote url</Text></TouchableOpacity></View></View>)}}

Your app should now look like the below

The next step is to make sure you have a sound file to use I will be using a sound file called “da.mp3” for this tutorial as it is a voice recording in Russian I made. For playing a local file on Android you will need to locate the below directory within your Android folder in the react-native project.

android/app/src/main/res

NOTE: The sound files you want to play MUST be lowercase and underscored if necessary.

Inside of the res folder create another folder called “raw”, this will contain your local sound file, I have now copied my sound file to that location.

if you want to play a sound file from your iOS simulator you will need to open your xcworkspace file in xcode (if you are using react-native 0.60 or greater) else open your xcodeproj file in xcode instead.

Once you have done that right click on your project name on the left hand side and click “Add files to yourprojectname”

Now look for your sound file on your hard-drive, be sure to tick the box labelled “Copy items if needed” and click “Add”. You will now see the sound file in your project.

We will now import the package in our App.js file using the below.

import Sound from 'react-native-sound';

We will then create a method called “PlayLocalSoundFile” and set the sound category to playback as we want to play a sound (this creates an audio session between the app and operating system so the device knows what type of audio action will happen in this method)

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

Afterwards we will need to load our sound (remember to change the sound file name to whatever you named yours) from the main app bundle and pass in an error callback to check for any errors, inside of this variable we play the sound too using the “.play” method, and if the sound successfully plays then a console log message is added as well as setting the volume of the sound, where 0.0 is the lowest and 1 is the highest. In addition, we also release the resources.

var mySound = new Sound('da.mp3',Sound.MAIN_BUNDLE,(error)=>{if(error){console.log('Error loading sound: ' + error);return;}else{mySound.play((success)=>{if(success){console.log('Sound playing')}else{console.log('Issue playing file');}})}});mySound.setVolume(0.9);
mySound.release();

We will now run this method on press of the first touchable opacity, so copy the below code into the touchable opacity component.

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

It should now look like the below.

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

Playing sound from remote URL

Playing sound from a remote url will be the exact same process apart from a few tweaks, so go ahead and create method named “PlayRemoteURLSoundFile”. This will contain our code to play the remote url sound.

Now set your category to playback like the below as again we want to play a sound not record.

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

We now create a variable that will be equal to a new Sound instance and the first parameter will be the url of the sound that you want to play, I have found a random sound from soundjay.com — https://www.soundjay.com/ambient/sounds/boarding-accouncement-1.mp3

Since we are not playing a sound file from the main bundle of the app we do not need to pass MAIN_BUNDLE, we can instead pass in null, and the third param will be an error callback. So now our method will be the same as the previous one for the local sound file. Our remote url method will look like the below.

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;}else{myRemoteSound.play((success)=>{if(success){console.log('Sound playing')}else{console.log('Issue playing file');}})}});myRemoteSound.setVolume(0.9);myRemoteSound.release();}

I have tested both sound files on both platforms and each method runs successfully and plays the file.

Note: When you test on an Android simulator if you get the error

“Could not initialize class org.codehaus.groovy.vmplugin.v7.Java7”

Try cleaning and rebuilding the project in Android studio as that occured when I was testing and that seemed to fix the issue.

Example Use case

When I have been developing apps in my spare time I have at times wanted to play a sound file when clicking on an icon on a row within the flat list.

When doing this I would have a column in the database table named “SoundFileName" which would be equal to the name of the sound file you want to play. So when you pull back your data for your flat list you can pull back the sound file name, place it in a method parameter and put this parameter in the first partner for the “new Sound” variable. That way when you click on a row it will look for that sound file name to play that you have stored locally or on a remote url somewhere. That is just my 2 cents, if anyone else has a better way of playing sound files when clicking on a flat list item feel free to respond to this article!

Below are a few code examples of how I have incorporated this.

Thank you very much for reading this article it would be much appreciated if you could clap the article and share with others ☺

Have a good say and stay safe

--

--