React Native module for playing sound clips

Last update: May 11, 2022

react-native-sound

React Native module for playing sound clips on iOS, Android, and Windows.

Be warned, this software is alpha quality and may have bugs. Test on your own and use at your own risk!

Feature matrix

React-native-sound does not support streaming. See #353 for more info. Of course, we would welcome a PR if someone wants to take this on.

In iOS, the library uses AVAudioPlayer, not 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
Pause
Resume
Stop
Reset
Release resource
Get duration
Get number of channels
Get/set volume
Get system volume
Set system volume
Get/set pan
Get/set loops
Get/set current time
Set speed

Installation

First install the npm package from your app directory:

npm install react-native-sound --save

Then link it automatically using:

react-native link react-native-sound

If you encounter this error

undefined is not an object (evaluating 'RNSound.IsAndroid')

you may additionally need to fully clear your build caches for Android. You can do this using

cd android
./gradlew cleanBuildCache

After clearing your build cache, you should execute a new react-native build.

If you still experience issues, know that this is the most common build issue. See #592 and the several issues linked from it for possible resolution. A pull request with improved documentation on this would be welcome!

Manual Installation Notes

Please see the Wiki for these details https://github.com/zmxv/react-native-sound/wiki/Installation

Help with React-Native-Sound

  • For react-native-sound developers
  • For help using react-native-sound

Demo project

https://github.com/zmxv/react-native-sound-demo

Player

https://github.com/benevbright/react-native-sound-playerview

Basic usage

First you'll need to add audio files to your project.

  • Android: Save your sound clip files under the directory android/app/src/main/res/raw. Note that files in this directory must be lowercase and underscored (e.g. my_file_name.mp3) and that subdirectories are not supported by Android.
  • iOS: Open Xcode and add your sound files to the project (Right-click the project and select Add Files to [PROJECTNAME])
// Import the react-native-sound module
var Sound = require('react-native-sound');

// Enable playback in silence mode
Sound.setCategory('Playback');

// Load the sound file 'whoosh.mp3' from the app bundle
// See notes below about preloading sounds within initialization code below.
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');
    }
  });
});

// Reduce the volume by half
whoosh.setVolume(0.5);

// Position the sound to the full right in a stereo field
whoosh.setPan(1);

// Loop indefinitely until stop() is called
whoosh.setNumberOfLoops(-1);

// Get properties of the player instance
console.log('volume: ' + whoosh.getVolume());
console.log('pan: ' + whoosh.getPan());
console.log('loops: ' + whoosh.getNumberOfLoops());

// Seek to a specific point in seconds
whoosh.setCurrentTime(2.5);

// Get the current playback point in seconds
whoosh.getCurrentTime((seconds) => console.log('at ' + seconds));

// Pause the sound
whoosh.pause();

// Stop the sound and rewind to the beginning
whoosh.stop(() => {
  // Note: If you want to play a sound after stopping and rewinding it,
  // it is important to call play() in a callback.
  whoosh.play();
});

// Release the audio player resource
whoosh.release();

Notes

  • To minimize playback delay, you may want to preload a sound file without calling play() (e.g. var s = new Sound(...);) during app initialization. This also helps avoid a race condition where play() may be called before loading of the sound is complete, which results in no sound but no error because loading is still being processed.
  • You can play multiple sound files at the same time. Under the hood, this module uses AVAudioSessionCategoryAmbient to mix sounds on iOS.
  • You may reuse a Sound instance for multiple playbacks.
  • On iOS, the module wraps AVAudioPlayer that supports aac, aiff, mp3, wav etc. The full list of supported formats can be found at https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/SupportedAudioFormatsMacOSX/SupportedAudioFormatsMacOSX.html
  • On Android, the module wraps android.media.MediaPlayer. The full list of supported formats can be found at https://developer.android.com/guide/topics/media/media-formats.html
  • On Android, the absolute path can start with '/sdcard/'. So, if you want to access a sound called "my_sound.mp3" on Downloads folder, the absolute path will be: '/sdcard/Downloads/my_sound.mp3'.
  • You may chain non-getter calls, for example, sound.setVolume(.5).setPan(.5).play().

Audio on React Native

Contributing

Pull requests welcome with bug fixes, documentation improvements, and enhancements.

When making big changes, please open an issue first to discuss.

License

This project is licensed under the MIT License.

GitHub

https://github.com/zmxv/react-native-sound
Comments
  • 1. Not working on IOS: Cannot read property 'IsAndroid' of undefined

    The error is regarding the following line of code in sound.js :

    var RNSound = require('react-native').NativeModules.RNSound;
    var IsAndroid = RNSound.IsAndroid;
    

    I have followed the instructions exactly as outlined for IOS, so I have no idea why I am getting this error. This module works perfectly on Android.

    Reviewed by Frosty92 at 2016-05-17 23:12
  • 2. IOS error Object {code: "ENSOSSTATUSERRORDOMAIN2003334207"

    error Object {code: "ENSOSSTATUSERRORDOMAIN2003334207", message: "The operation couldn’t be completed. (OSStatus error 2003334207.)", nativeStackIOS: Array[17], domain: "NSOSStatusErrorDomain"}

    It is not work if I using mp3 file in my component folder Music/ music.js background1.mp3

    playSound() { var s = new Sound('background2.mp3', Sound.DOCUMENT, (e) => { if (e) { console.log('error', e); } else { console.log('duration', s.getDuration()); s.play(); } }); }

    Reviewed by keung725 at 2016-08-28 12:24
  • 3. [Android] java.lang.RuntimeException - Possible Race Condition

    I've just observed this Crash in the wild - i could imagine that it could be some sort of Race Condition or maybe both - onError and onCompletion - is called at a certain condition.

    Fatal Exception: java.lang.RuntimeException: Illegal callback invocation from native module. This callback type only permits a single invocation from native code.
           at com.facebook.react.bridge.CallbackImpl.invoke(CallbackImpl.java:32)
           at com.zmxv.RNSound.RNSoundModule$1.onCompletion(RNSoundModule.java:81)
           at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:2538)
           at android.os.Handler.dispatchMessage(Handler.java:102)
           at android.os.Looper.loop(Looper.java:135)
           at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
           at java.lang.Thread.run(Thread.java:818)
    
    Reviewed by K-Leon at 2017-02-09 15:36
  • 4. Cannot read property 'IsAndroid' of undefined

    On iOS, in fresh project generated by latest version of create-react-native-app: RNSound is not defined in NativeModules of react-native.

    "dependencies": {
        "expo": "^18.0.3",
        "react": "16.0.0-alpha.12",
        "react-native": "^0.45.1",
        "react-native-sound": "^0.10.3"
      }
    
    Reviewed by findzen at 2017-06-26 14:40
  • 5. Can't load file on device

    Hi, I'm working on a simple soundboard app (source code is available at https://github.com/sexykodo/mlcSoundboard) that automatically fetches remote audio files according to a JSON and puts them in MainBundle with RNFetchBlob.

    It's something like this:

    fetchRemoteFile = (obj) => {
            RNFetchBlob
                .config({
                    path : RNFetchBlob.fs.dirs.MainBundleDir + encodeURI(obj.Path) //target path
                })
                .fetch('GET', MAIN_URL + encodeURI(obj.Path), {})
                .then((res) => {
                    // the conversion is done in native code
                    // the following conversions are done in js, it's SYNC
                    console.log('The file saved to ', res.path())
                })
                // Status code is not 200
                .catch((errorMessage, statusCode) => {
                    // error handling
                    console.log(errorMessage)
                })
        }
    
    

    In this way I can dynamically sync local files with remote ones (I want the soundboard to work offline). Everything works like a charm on IOS Simulator.

    On physical device though, when I load the local file I get an errorcode "ENSOSSTATUSERRORDOMAIN2003334207", wich is similar to #64 and probably caused by files not being included in Resources.

    Is it actually possible to programmatically save an audio file (with RNFetchBlob) and play it?

    Thanks in advance

    Reviewed by maurovisintin at 2016-12-19 14:54
  • 6. The operation couldn’t be completed. (OSStatus error -10875.)

    Hello, guys. I have the following error when trying to play a sound. I will attach an image of the error below. Here is my code:

    import Sounddd from 'react-native-sound';
    const sTest = new Sounddd('test.mp3', Sounddd.MAIN_BUNDLE, (error) => {
    			if (error) {
    				console.log('failed to load the sound', error);
    				return;
    			}
    			// loaded successfully
    			console.log('duration in seconds: ' + sTest.getDuration() + 'number of channels: ' + sTest.getNumberOfChannels());
    		});
    
    		sTest.play((success) => {
    			if (success) {
    				console.log('successfully finished playing');
    			} else {
    				console.log('playback failed due to audio decoding errors');
    			}
    		});
    

    screen shot 2017-02-27 at 1 11 36 pm screen shot 2017-02-27 at 1 11 07 pm

    Reviewed by zakster12 at 2017-02-27 11:16
  • 7. cannot compile android with RN 0.53

    I have:

    • react-native-cli: 2.0.1
    • react-native: 0.53.0

    And i get:

    node_modules/react-native-sound/android/src/main/java/com/zmxv/RNSound/RNSoundModule.java:43: error: cannot find symbol
        final ReactContext reactContext = this.context;
              ^
      symbol:   class ReactContext
      location: class RNSoundModule
    

    any idea? 0.53 is not supported?

    Reviewed by badpenguin at 2018-02-20 14:19
  • 8. 0.10.4 Cannot read property 'IsAndroid' of undefined

    "react": "^16.2.0", "react-native": "^0.51.0" it is my package version,i found Cannot read property 'IsAndroid' of undefined this error on android ,can you help me!

    Reviewed by zkeyword at 2018-01-25 07:27
  • 9. Troubleshooting "undefined is not an object (evaluating 'RNSound.IsAndroid')"

    The most common problem developers experience with this library is undefined is not an object (evaluating 'RNSound.IsAndroid').

    This is caused by the library's native code not being linked. This is a tooling issue and seems to have a variety of different specific resolutions, depending on your environment.

    See these related threads:

    • #36 (48 comments)
    • #215 (30 comments)
    • #128 (16 comments)
    • #471 (14 comments)

    If you're experiencing this issue and want help troubleshooting it, please review those threads first. If you aren't able to resolve the problem, please open a new issue with a link to a project that reproduces the project, information about your environment, and information about the steps you have tried.

    Meanwhile, it would be very helpful if someone could collect the troubleshooting advice from those sources, and write it up in the readme.

    Note, also reported here:

    • #57
    • #352
    • #446
    • #541
    • #567
    Reviewed by paulmelnikow at 2019-07-12 19:03
  • 10. RNSound.IsAndroid bug

    React Native - 0.42.0 React Native Sound - 0.9.1

    I have only this snippet of code, nothing special:

    const whoosh = new Sound(requireAudio, (error) => {
                if (error) {
                    console.log('error', error);
                } else {
                    whoosh.setSpeed(1);
                    console.log('duration', whoosh.getDuration());
                    whoosh.play(() => whoosh.release());
                }
            });
    

    but the error is shown when it's trying to import the module, not on execution screen shot 2017-03-07 at 1 41 09 pm

    Reviewed by zakster12 at 2017-03-07 11:43
  • 11. Is this library supported anymore?

    I am having issues with an iPhone 7 specifically. Everything runs perfectly in simulator then on device it never invokes the .play() callback. Its very strange. I see theres other forks with active maintenance. Are the current contributors active? If I were to debug/fix my issues (assuming its a bug) would it be merged?

    Reviewed by moaxaca at 2017-02-07 06:20
  • 12. Uncaught Error - bundle/application/.app is not function

    :beetle: Description

    Getting this error in only iOS immediately at app launch.

    Simulator Screen Shot - iPhone 13 mini - 2022-04-24 at 19 47 18

    :beetle: What have you tried?

    I have tried all the troubleshooting like clean, remove and fresh install of node_modules and pod but doesn't help.

    :beetle: Please post your code:

    // Please post your code
    

    :bulb: Possible solution

    Is your issue with...

    • ios

    Are you using...

    • [Y ] React Native CLI (e.g. react-native run-android)

    Which versions are you using?

    • React Native Sound: 0.11.0
    • React Native:0.64.1
    • iOS: 15.4
    • Android:
    • Windows:

    Does the problem occur on... Both

    • [ ] Simulator
    • [ ] Device
    Reviewed by Balasnest at 2022-04-24 14:28
  • 13. [Windows] Project RNSoundModule is not compatible with native

    :beetle: Description

    I installed the dependency recently and ran react-native link react-native-sound. when i run react-native run-windows I get this message:

    error NU1201: Project RNSoundModule is not compatible with native (native,Version=v0.0). Project RNSoundModule supports: uap10.0 (UAP
    ,Version=v10.0)
    

    What could be the problem?

    Thanks.

    :beetle: What have you tried?

    :beetle: Please post your code:

    // Please post your code
    

    :bulb: Possible solution

    Is your issue with...

    • [ ] iOS
    • [ ] Android
    • [x] Windows

    Are you using...

    • [x] React Native CLI (e.g. react-native run-android)
    • [ ] Expo
    • [ ] Other: (please specify)

    Which versions are you using?

    • React Native Sound: 0.11.2
    • React Native: 0.68.1
    • Windows: 0.68.1

    Does the problem occur on...

    • [x] Simulator
    • [ ] Device
    Reviewed by dincozdemir at 2022-04-23 16:52
  • 14. `mixWithOthers` does not function correctly on iOS.

    :beetle: Description

    mixWithOthers permanently stops audio streams on iOS from other apps such as Spotify, even though mixWithOthers is declared as true.

    :beetle: What is the observed behavior?

    Audio streams are stopped.

    :beetle: What is the expected behavior?

    The sound being played from another app is played along side the sound from your app.

    :beetle: Please post your code:

    In a brand new template app:

    1. npx react-native init TestClean
    2. npm i react-native-sounds
    3. pod install
    4. Add loop.mp3 to the xcode project.
    5. Check off background modes: Audio, AirPlay, and Picture in Picture, External accessory communication
    6. In App.js:
    import Sound from "react-native-sound";
    
    Sound.setCategory(`Playback`, true);
    Sound.setMode(`Default`);
    
    let sound = new Sound(`loop.mp3`, Sound.MAIN_BUNDLE, error => {
      sound.play();
      if (error) {
        console.error(error);
      } else {
        console.log('success');
      }
    });
    

    :bulb: Possible solution

    According to the developer docs for AVAudioSessionCategoryOptionAllowBluetooth:

    You can set this option only if the audio session category is AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryRecord.

    However, in https://github.com/zmxv/react-native-sound/blob/1aa45f25c8c03ea5c17fac18564c3928bd023113/RNSound/RNSound.m#L175-L180

    It is setting this option regardless of the category.

    :bulb: Is there a workaround?

    Removing this declaration AVAudioSessionCategoryOptionAllowBluetooth no longer causes the sound to interrupt other apps. I also checked with bluetooth headphones, and there was no difference in behavior with or without this option being present.

    Note: I tested this workaround only on playback category, iOS 15.4.

    Using patch-package:

    diff --git a/node_modules/react-native-sound/RNSound/RNSound.m b/node_modules/react-native-sound/RNSound/RNSound.m
    index df3784e..aa97df6 100644
    --- a/node_modules/react-native-sound/RNSound/RNSound.m
    +++ b/node_modules/react-native-sound/RNSound/RNSound.m
    @@ -175,8 +175,7 @@ - (NSDictionary *)constantsToExport {
         if (category) {
             if (mixWithOthers) {
                 [session setCategory:category
    -                     withOptions:AVAudioSessionCategoryOptionMixWithOthers |
    -                                 AVAudioSessionCategoryOptionAllowBluetooth
    +                     withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                error:nil];
             } else {
                 [session setCategory:category error:nil];
    

    :bulb: If the bug is confirmed, would you be willing to create a pull request?

    Sure

    Is your issue with...

    • [x] iOS
    • [ ] Android
    • [ ] Windows

    Are you using...

    • [x] React Native CLI (e.g. react-native run-android)
    • [ ] Expo
    • [ ] Other: (please specify)

    Which versions are you using?

    • React Native Sound: 0.11.2
    • React Native: 0.67.4
    • iOS: iOS 15.4
    • Android: n/a
    • Windows: n/a

    Does the problem occur on...

    • [ ] Simulator
    • [x] Device

    If your problem is happening on a device, which device?

    • Device: iPhone 13 Pro Max
    Reviewed by dsf3449 at 2022-04-04 20:38
  • 15. [iOS] Can't build with react-native 0.67.4

    :beetle: Description

    I'm trying to build with react-native 0.67.4 bare react-app on iOS but it always fails with the following errors:

    node_modules/react-native-sound/RNSound/RNSound.m:236:44: Implicit declaration of function 'RCTJSErrorFromNSError' is invalid in C99
    
    node_modules/react-native-sound/RNSound/RNSound.m:236:44: Declaration of 'RCTJSErrorFromNSError' must be imported from module 'React.RCTUtils' before it is required
    
    node_modules/react-native-sound/RNSound/RNSound.m:236:44: Conflicting types for 'RCTJSErrorFromNSError'
    

    It works fine with android though.

    XCode: Version 13.3 (13E113)

    :beetle: What is the observed behavior?

    Build fails when building for ios.

    :beetle: What is the expected behavior?

    It should not fail building.

    :beetle: Please post your code:

    N/A

    :bulb: Does the problem have a test case?

    :bulb: Possible solution

    :bulb: Is there a workaround?

    :bulb: If the bug is confirmed, would you be willing to create a pull request?

    Is your issue with...

    • [x] iOS
    • [ ] Android
    • [ ] Windows

    Are you using...

    • [x] React Native CLI (e.g. react-native run-android)
    • [ ] Expo
    • [ ] Other: (please specify)

    Which versions are you using?

    • React Native Sound: 0.11.2
    • React Native: 0.67.4
    • iOS: 12
    • Android:
    • Windows:

    Does the problem occur on...

    • [x] Simulator
    • [x] Device

    If your problem is happening on a device, which device?

    • Device: N/A
    Reviewed by aprilmintacpineda at 2022-03-21 14:08
  • 16. Sound never plays again once I release it, even on component re-load

    :beetle: Description

    I want to play some music when user loads into the app and stays on a specific screen. I can get the track to play at the start however, once they leave the screen and come back to it later, the sound doesn't play anymore. Any help would be appreciated, thanks.

    :beetle: What have you tried? Changing tracks, different methods of playing audio etc.

    //audio setup outside of component function
    var Sound = require('react-native-sound');
    
    var background = new Sound('onboarding.mp3', Sound.MAIN_BUNDLE, (error) => {
      if (error) {
          console.log('failed to load the sound', error);
          return;
        } else {
          background.play((success)=> console.log(success)); // have to put the call to play() in the onload callback
      }
      });
    
    //then playing tracks with following in useEffect
    background.setVolume(1);
    
    background.play(success => {
      if (success) {
        console.log('successfully finished playing');
      } else {
        console.log('playback failed due to audio decoding errors');
      }
    });
    
    //then I run this after component unmounts
    background.stop(() => {});
    background.release();
    

    Is your issue with...

    • [ x] iOS
    • [x ] Android
    • [ ] Windows

    Are you using...

    • [x ] React Native CLI (e.g. react-native run-android)
    • [ ] Expo
    • [ ] Other: (please specify)

    Which versions are you using?

    • React Native Sound: "^0.11.1",
    • React Native: "0.63.4",
    • iOS: 15
    • Android: Oreo

    Does the problem occur on...

    • [x ] Simulator
    • [x ] Device

    If your problem is happening on a device, which device?

    • Device: iphone 12, pixel 3
    Reviewed by cgruca at 2022-03-11 01:38
react-native-sound demo project for iOS and Android
react-native-sound demo project for iOS and Android

react-native-sound-demo react-native-sound demo project for iOS and Android. There are a series of basic test for different audio formats and location

Mar 31, 2022
Simplest Sound Recorder for React Native

react-native-sound-recorder No-hassle Sound Recorder for React Native. There are existing libraries out in the wild https://github.com/MisterAlex95/re

Apr 27, 2022
iOS & Android react native module to play an audio stream, with background support and media controls
iOS & Android react native module to play an audio stream, with background support and media controls

react-native-audio-streaming THIS PROJECT IS NOT MAINTAINED react-native-audio-streaming is not maintained anymore. The main purpose was to play shout

Mar 25, 2022
React Native Android module audio streaming AAC

React Native Android Audio Streaming AAC A react native wrapper for aacdecoder-android. Setup android/settings.gradle ... include ':react-native-andro

Feb 17, 2021
React Native module for PhotoEditor SDK
React Native module for PhotoEditor SDK

React Native module for PhotoEditor SDK Check out our video tutorial for a step-by-step integration guide which also details advanced SDK features, su

Apr 24, 2022
React Native module for VideoEditor SDK

React Native module for VideoEditor SDK Check out our video tutorial for a step-by-step integration guide which also details advanced SDK features, su

May 13, 2022
A React Native module to play audio on Android

react-native-audio-player A React Native module to play audio on Android Installation First you need to install react-native-audio-player: npm install

Mar 1, 2019
A fully fledged audio module created for music apps. Provides audio playback, external media controls, chromecast support, background mode and more!
A fully fledged audio module created for music apps. Provides audio playback, external media controls, chromecast support, background mode and more!

A fully-fledged audio module created for music apps. Provides audio playback, external media controls, background mode and more! ⚠️ V2 Migration Guide

May 12, 2022
This repo has been moved to https://github.com/react-native-webrtc/react-native-incall-manager

react-native-incall-manager Handling media-routes/sensors/events during a audio/video chat on React Native Purpose: The purpose of this module is to h

Dec 22, 2021
Native Video editing/trimming/compressing :movie_camera: library for React-Native
Native Video editing/trimming/compressing  :movie_camera: library for React-Native

react-native-video-processing Getting Started npm install react-native-video-processing --save yarn add react-native-video-processing You can check te

May 9, 2022
A Camera component for React Native. Also supports barcode scanning!
A Camera component for React Native. Also supports barcode scanning!

React Native Camera ?? ?? Looking for maintainers and backers ?? ?? See this issue We are looking for maintainers for this package, or to depreciate t

May 15, 2022
Audio recorder library for React Native

Record audio in iOS or Android React Native apps. MAINTENANCE STATUS This project is no longer actively maintained by me, the original author. I will

May 9, 2022
Cross-platform audio library for React Native
Cross-platform audio library for React Native

This is a cross-platform (Android and iOS) audio library for React Native. Both audio playback and recording is supported. In addition to basic functi

May 8, 2022
A high performance, easy to use, rock solid camera library for React Native apps.
A high performance, easy to use, rock solid camera library for React Native apps.

?? React Native Camera Kit A high performance, easy to use, rock solid camera library for React Native apps. Cross Platform (iOS and Android) Optimize

May 11, 2022
📷 A React Native component providing images selection from camera roll
📷  A React Native component providing images selection from camera roll

react-native-camera-roll-picker CameraRoll Picker component for React native Requires react-native >=0.43.0 Add to Project Install component through n

Mar 31, 2022
A text-to-speech library for React Native.

React Native Speech React Native Speech is a text-to-speech library for React Native. Documentation Install Usage Example Methods License Install npm

Apr 5, 2022
A modern and comprehensive CameraRoll/iCloud-library-API for React Native 📸 📹

react-native-photos-framework Example project NOTE: This is not a GUI-component, it's an API. The example project just shows off some of the the capab

Apr 19, 2022
Small audio player library for react native

react-native-audioplayer Small audio player library for react native ##Installation First you need to install react-native-audioplayer: npm install re

Oct 26, 2021
Media player for React Native

React-Native-Player Media Player for React-Native Only Android support now. Integrate Android Install via npm npm i react-native-player --save-dev Add

Mar 24, 2021