react-native-nitro-sound

repository·main·Indexed 19 days ago

https://github.com/hyochan/react-native-nitro-sound

A high-performance audio recording and playback library for React Native built on NitroModules. It provides zero bridge overhead and full type safety across iOS, Android, and Web. The library includes a singleton Sound instance for basic use, a createSound() factory for multiple independent audio streams, and a useSound React hook for reactive state management. It also provides an Expo Config Plugin to automate native permissions for microphone and storage access.

Tokens
14.6K
Snippets
48
Records
60
Agent score
74%

What's inside react-native-nitro-sound

  1. Reload the application

    main

    If you need to perform a full reload to reset the app state, use the following platform-specific shortcuts:

    - Android: Press <kbd>R</kbd> twice or select "Reload" from the Dev Menu (<kbd>Ctrl</kbd> + <kbd>M</kbd> on Windows/Linux, <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> on macOS).
    - iOS: Press <kbd>R</kbd> in the iOS Simulator.
  2. Post-installation setup for iOS, Android, and Web

    main

    After installing the packages, perform the following platform-specific steps:

    iOS

    Run pod install to link the native modules:

    npx pod-install

    Note: If resolution fails, try npx pod-install --repo-update. RN 0.81+ requires Xcode >= 16.1.

    Android

    No additional steps are required; the module uses autolinking.

    Web

    For React Native Web support, install react-native-web and configure your webpack alias:

    // webpack.config.js
    module.exports = {
      resolve: {
        alias: {
          'react-native': 'react-native-web',
        },
      },
    };
    npx pod-install
  3. Run the Example App

    main

    To run the included example project, you must use Yarn from the repository root because it uses a Yarn workspace.

    1. Install dependencies and build the library:
      yarn
      yarn prepare
    2. Start the development server:
      yarn start
    3. Run on your platform:
      • iOS:
        (cd example/ios && pod install)
        yarn example ios
      • Android:
        yarn example android
    yarn
    yarn prepare
    yarn start
    yarn example ios
  4. Add react-native-nitro-sound plugin to app.json or app.config.js

    main

    Add react-native-nitro-sound to the plugins array in your Expo configuration file (app.json or app.config.js).

    Default Usage

    Use this configuration to apply default permissions and settings:

    {
      "expo": {
        "plugins": [
          "react-native-nitro-sound"
        ]
      }
    }

    Custom Microphone Permission Text

    If you want to provide a custom description for the microphone usage prompt on iOS, pass an options object with the microphonePermissionText key:

    {
      "expo": {
        "plugins": [
          [
            "react-native-nitro-sound",
            {
              "microphonePermissionText": "This app needs access to your microphone to record audio messages."
            }
          ]
        ]
      }
    }
    {
      "expo": {
        "plugins": [
          [
            "react-native-nitro-sound",
            {
              "microphonePermissionText": "This app needs access to your microphone to record audio messages."
            }
          ]
        ]
      }
    }
  5. Configure react-native-nitro-sound with Expo Config Plugin

    main

    To use react-native-nitro-sound in an Expo project, use the react-native-nitro-sound config plugin. This plugin automates the necessary native configuration for both Android and iOS.

    Android Configuration

    The plugin automatically adds the following permissions to your AndroidManifest.xml:

    • android.permission.RECORD_AUDIO
    • android.permission.WRITE_EXTERNAL_STORAGE
    • android.permission.READ_EXTERNAL_STORAGE

    iOS Configuration

    The plugin automatically adds the NSMicrophoneUsageDescription key to your Info.plist.

  6. Use the Sound singleton for basic recording and playback

    main

    The default export Sound is a singleton instance. It is suitable for simple applications that only require one recorder or one player at a time.

    Recording Workflow

    1. Use addRecordBackListener to listen for progress and metering.
    2. Call startRecorder() to begin. You can optionally provide a URI, an AudioSet configuration, and a meteringEnabled boolean.
    3. Use pauseRecorder(), resumeRecorder(), or stopRecorder() to control the session.
    4. Always call removeRecordBackListener() when finished to prevent memory leaks.

    Playback Workflow

    1. Use addPlayBackListener for progress updates and addPlaybackEndListener for completion.
    2. Call startPlayer() with an optional URI or HTTP headers.
    3. Control playback with pausePlayer(), resumePlayer(), stopPlayer(), or seekToPlayer(milliseconds).
    4. Adjust audio with setVolume(0.0 - 1.0) and setPlaybackSpeed(0.5 - 2.0).
    5. Clean up listeners using removePlayBackListener() and removePlaybackEndListener().

    Utility Methods

    • mmssss(seconds): Converts seconds to a minute:second:millisecond string.
    • mmss(seconds): Converts seconds to a minute:second string.
    import Sound, { RecordBackType, PlayBackType } from 'react-native-nitro-sound';
    
    // Recording example
    const onStartRecord = async () => {
      Sound.addRecordBackListener((e: RecordBackType) => {
        console.log('Position:', e.currentPosition);
      });
    
      const uri = await Sound.startRecorder();
      console.log('Saved to:', uri);
    };
    
    const onStopRecord = async () => {
      await Sound.stopRecorder();
      Sound.removeRecordBackListener();
    };
    
    // Playback example
    const onStartPlay = async () => {
      Sound.addPlayBackListener((e: PlayBackType) => {
        console.log('Progress:', e.currentPosition);
      });
    
      await Sound.startPlayer('https://example.com/audio.mp3');
    };
  7. Migrate from react-native-audio-recorder-player

    main

    If you are migrating from react-native-audio-recorder-player (version 3.x or earlier), the API remains largely the same. You only need to update your import statement:

    - import AudioRecorderPlayer from 'react-native-audio-recorder-player';
    + import Sound from 'react-native-nitro-sound';
  8. Build and run the iOS app

    main

    For iOS, you must first install CocoaPods dependencies. If this is your first time or you have updated native dependencies, run bundle install and bundle exec pod install before running the app command.

    # Install CocoaPods dependencies
    bundle install
    bundle exec pod install
    
    # Run the app
    # Using npm
    npm run ios
    
    # OR using Yarn
    yarn ios
  9. Install react-native-nitro-sound

    main

    To use react-native-nitro-sound, you must install both the library and its required dependency react-native-nitro-modules.

    Installation Commands

    Using yarn:

    yarn add react-native-nitro-sound react-native-nitro-modules

    Using npm:

    npm install react-native-nitro-sound react-native-nitro-modules

    It is recommended to align your React Native dependencies using @rnx-kit/align-deps:

    npx @rnx-kit/align-deps --requirements react-native@0.81 --write
    yarn add react-native-nitro-sound react-native-nitro-modules
  10. Configure audio settings with AudioSet

    main

    You can fine-tune recording and playback quality using an AudioSet object. The library handles platform-specific mapping automatically.

    Cross-Platform Configuration

    Use common keys for consistent behavior across iOS and Android:

    • AudioSamplingRate: Sampling rate in Hz.
    • AudioEncodingBitRate: Bit rate in bps.
    • AudioChannels: Number of channels (1 for mono, 2 for stereo).

    iOS Specific Configuration

    Use keys with the IOS suffix:

    • AVSampleRateKeyIOS
    • AVFormatIDKeyIOS (use AVEncodingOption)
    • AVEncoderAudioQualityKeyIOS (use AVEncoderAudioQualityIOSType)
    • AVNumberOfChannelsKeyIOS
    • AVModeIOS (options: 'gameChatAudio', 'measurement', 'moviePlayback', 'spokenAudio', 'videoChat', 'videoRecording', 'voiceChat', 'voicePrompt')

    Android Specific Configuration

    Use keys with the Android suffix:

    • AudioEncoderAndroid (use AudioEncoderAndroidType)
    • AudioSourceAndroid (use AudioSourceAndroidType)

    Important: Legacy Android keys like AudioSamplingRateAndroid are deprecated. Use the common AudioSamplingRate instead.

    Android Quality Presets

    If AudioQuality is omitted, Android defaults to high:

    • low: 22050 Hz, 64 kbps, mono
    • medium: 44100 Hz, 128 kbps, mono
    • high: 48000 Hz, 192 kbps, stereo (Default)

    Explicitly setting AudioSamplingRate, AudioEncodingBitRate, or AudioChannels will override these presets.

    // Cross-platform example
    const audioSet = {
      AudioSamplingRate: 44100,
      AudioEncodingBitRate: 128000,
      AudioChannels: 1,
    };
    
    // iOS specific example
    const iosSet = {
      AVSampleRateKeyIOS: 44100,
      AVFormatIDKeyIOS: AVEncodingOption.aac,
      AVModeIOS: 'measurement',
    };
    
    // Start recorder with config
    const uri = await Sound.startRecorder(undefined, audioSet, true);