Skip to content
 
 

Repository files navigation

@PatriciaSauer/react-native-sound

Package version License: MIT

Fork of zmxv/react-native-sound. React Native module for playing sound clips on iOS, Android, and Windows.

This fork keeps upstream behavior but adds an Effects audio category, clearer Sound.setCategory documentation, and Android routing tuned so UI/game SFX follow media volume and do not interrupt background music. Report bugs and feature requests on this repository.

Upstream remains useful for context (e.g. #353, #592); this README documents this package first.

Be warned: the original project calls itself alpha-quality. Test on real devices and use at your own risk.

What this fork changes

Change Why it matters
Sound.setCategory('Effects') Android: AudioAttributes with CONTENT_TYPE_SONIFICATION and USAGE_GAME (API 28+) or USAGE_MEDIA (API 21–27). Never requests audio focus, so other apps’ audio keeps playing. Uses media volume (unlike USAGE_ASSISTANCE_SONIFICATION, which is often tied to notification/accessibility volume and can be silent when notification sounds are off).
iOS Effects Maps to plain Ambient (mix-friendly by default; mixWithOthers is ignored).
Docs Full Sound.setCategory reference: category matrix (Android vs iOS), meaning of mixWithOthers, and the JS default (false when omitted).

Everything else (API surface, native module name, autolinking) is largely unchanged from upstream, so existing react-native-sound tutorials still apply—swap the package name in imports and install commands.

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 exact loop count
Get/set current time
Set speed
Sound.setCategory('Effects') (SFX + mix with other audio)

Installation

From your app directory, install this package (not the unscoped react-native-sound name on npm unless you intentionally use upstream):

npm

npm install @PatriciaSauer/react-native-sound

Yarn

yarn add @PatriciaSauer/react-native-sound

pnpm

pnpm add @PatriciaSauer/react-native-sound

Directly from GitHub (lockfile will pin a commit until you refresh it):

npm install github:PatriciaSauer/react-native-sound

The package.json name field (@PatriciaSauer/react-native-sound) is what you import in JS. If that name is not published on the public npm registry yet, use GitHub (or a private registry / npm pack) until you run npm publish.

If you publish under a different scope or unscoped name, use that string in npm install / import instead.

React Native 0.60 and above: native modules are autolinked; no react-native link needed.

Older React Native: use react-native link with this package per the React Native linking docs for your version.

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 (advanced)

Upstream wiki (still largely applicable): Installation.

Support

Demo project

https://github.com/zmxv/react-native-sound-demo (upstream demo; use this package name in your app when trying it)

Player

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

Quick start: SFX without interrupting other apps’ audio

Call setCategory before creating Sound instances.

import Sound from '@PatriciaSauer/react-native-sound';

Sound.setCategory('Effects');

const pop = new Sound('pop.mp3', Sound.MAIN_BUNDLE, (err) => {
  if (!err) pop.play();
});

On Android, Effects skips audio focus and uses media-volume-friendly attributes; on iOS, Effects is an alias for Ambient. See Sound.setCategory below for details.

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 this package (default export is the Sound constructor)
var Sound = require('@PatriciaSauer/react-native-sound');

// Typical: Playback for “main” app audio; use 'Effects' for short SFX that must not duck Spotify, etc.
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();

Sound.setCategory(category, mixWithOthers?)

Configure how your app interacts with the system audio session before you create Sound instances. Category and routing are applied in native code when each sound is prepared (when the Sound constructor runs).

Sound.setCategory('Playback', true);
  • Windows: setCategory is a no-op (native module does not implement it).

Second argument: mixWithOthers

This flag means “prefer to mix with other apps’ audio” versus “prefer to take focused control,” but the exact behavior is platform-specific (see below).

Default in JavaScript: Sound.setCategory is implemented as function (category, mixWithOthers = false). If you omit the second argument, it defaults to false.

Value Android iOS
true Does not call requestAudioFocus when play() runs, so other apps’ audio is less likely to be ducked or paused. Adds MixWithOthers for Playback / PlayAndRecord / MultiRoute, and AllowBluetooth for Record / PlayAndRecord. Options AVAudioSession does not accept for the category are dropped instead of being passed (passing one makes setCategory fail and leaves the previous category active).
false Calls requestAudioFocus on play() (unless category is Effects; see table below). Sets the AVAudioSession category without those mixing options.

Special case — Effects: On Android, Effects never requests audio focus, regardless of mixWithOthers. On iOS, Effects maps to plain Ambient (already mix-friendly); the second argument is ignored.

Category names: Android vs iOS

The same string is passed to both platforms, but native code only handles the names each platform defines. If a name is not supported on a platform, Android logs an error and leaves the default stream routing for that player; iOS leaves the session category unchanged for unknown names.

Category Android iOS
Playback MediaPlayer audio stream: STREAM_MUSIC. AVAudioSessionCategoryPlayback.
Ambient STREAM_NOTIFICATION. AVAudioSessionCategoryAmbient.
SoloAmbient Not mapped (error log). AVAudioSessionCategorySoloAmbient.
Record Not mapped (error log). AVAudioSessionCategoryRecord.
PlayAndRecord Not mapped (error log). AVAudioSessionCategoryPlayAndRecord.
AudioProcessing Not mapped (error log). AVAudioSessionCategoryAudioProcessing (iOS only).
MultiRoute Not mapped (error log). AVAudioSessionCategoryMultiRoute.
System STREAM_SYSTEM. Not mapped (no-op).
Voice STREAM_VOICE_CALL. Not mapped (no-op).
Ring STREAM_RING. Not mapped (no-op).
Alarm STREAM_ALARM. Not mapped (no-op).
Effects API 21+: CONTENT_TYPE_SONIFICATION with USAGE_GAME (API 28+) or USAGE_MEDIA (API 21–27). Avoids USAGE_ASSISTANCE_SONIFICATION, which often follows notification/accessibility volume (silent when notification sounds are off). Older API: STREAM_MUSIC. Never takes audio focus. Plain Ambient (second argument ignored).

For short UI or game sound effects while music from another app (or your own music player) should keep playing, use Effects (and on other categories use mixWithOthers: true if you want to avoid audio focus on Android).

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 (several Sound instances).
    • iOS — other apps’ audio: Sound.setCategory('Ambient') or Sound.setCategory('Effects') is enough for typical mixing: both use AVAudioSessionCategoryAmbient, which mixes with other apps by default. Playback is stricter: Sound.setCategory('Playback') sets Playback without MixWithOthers, so other apps’ audio is more likely to duck or stop—use Sound.setCategory('Playback', true) when you want to mix with them. Other categories follow the same pattern as Playback: pass true only when you need those mixing options.
    • Android: Ambient / Playback / most categories still use the second argument for audio focus (default false requests focus on play()). Use true to avoid that, or use Effects, which never requests focus regardless of the boolean.
  • 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 are welcome against PatriciaSauer/react-native-sound (bug fixes, docs, enhancements). For larger changes, open an issue first so direction is agreed.

If a change belongs in the wider ecosystem, consider offering the same patch upstream as well.

License

Licensed under the MIT License.

The software is based on react-native-sound by Zhen Wang (see LICENSE for the original copyright notice). Fork-specific changes are also under MIT unless noted otherwise.

About

React Native module for playing sound clips

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages