react-native-sound

repository·master·Indexed 25 days ago

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

A cross-platform audio playback library for React Native supporting iOS, Android, and Windows. It allows playing sound clips, sound effects, and background music with full TypeScript support and compatibility with the React Native New Architecture (TurboModules). The library provides controls for volume, panning, looping, and playback speed, and supports loading audio from the app bundle, documents directory, library directory, absolute paths, or remote URLs.

Tokens
3.4K
Snippets
9
Records
21
Agent score
83%

What's inside react-native-sound

  1. Configure audio files for iOS

    master

    For iOS, you must manually add audio files to your Xcode project bundle:

    1. Open your project in Xcode.
    2. Right-click your project and select "Add Files to [PROJECT]".
    3. Select your audio files and ensure they are added to the app target.
  2. Configure audio files for Android

    master

    For Android, audio files must be placed in the android/app/src/main/res/raw/ directory.

    Naming Requirements:

    • Use lowercase filenames.
    • Use underscores (_) instead of spaces or special characters.
    • Do not use subdirectories.

    Example structure:

    android/app/src/main/res/raw/
    ├── whoosh.mp3
    └── button_click.wav
    android/app/src/main/res/raw/
    ├── whoosh.mp3        ✅ Correct
    ├── button_click.wav  ✅ Correct
    └── my-sound.mp3      ❌ Use underscores: my_sound.mp3
  3. Build and run the iOS app

    master

    For iOS, you must first install CocoaPods dependencies. If this is a new project or you have updated native dependencies, run bundle install and bundle exec pod install first. Then, use the following command to launch the application on an iOS Simulator or connected device.

    # Install CocoaPods dependencies
    bundle install
    bundle exec pod install
    
    # Using npm
    npm run ios
    
    # OR using Yarn
    yarn ios
  4. Reload the application

    master

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

    • Android: Press the <kbd>R</kbd> key twice, or open the Dev Menu via <kbd>Ctrl</kbd> + <kbd>M</kbd> (Windows/Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (macOS) and select "Reload".
    • iOS: Press <kbd>R</kbd> in the iOS Simulator.
  5. Optimize playback and avoid race conditions

    master

    To minimize playback delay and avoid race conditions where play() is called before the sound has finished loading, preload your sound files during app initialization by creating a new Sound instance without immediately calling .play().

    Example:

    // Preload during initialization
    var s = new Sound('my_sound.mp3', Sound.REQUIRES_AUDIO_MODULE_INSTANCE, (error) => {
      if (error) {
        console.log('failed to load the sound', error);
        return;
      }
    });
    
    // Later in your app logic, call play()
    s.play();
    var s = new Sound(...);
  6. Access files via absolute paths on Android

    master

    On Android, you can access sound files using absolute paths. For files located in the Downloads folder, the path typically starts with /sdcard/.

    Example path for my_sound.mp3 in Downloads: /sdcard/Downloads/my_sound.mp3.

  7. Troubleshoot `RNSound.IsAndroid` undefined error

    master

    If you encounter the error undefined is not an object (evaluating 'RNSound.IsAndroid'), it usually indicates a linking issue. Follow these steps to resolve it:

    1. Clear build cache:
      cd android && ./gradlew cleanBuildCache
    2. Reset Metro cache:
      npx react-native start --reset-cache
    3. Clean and rebuild:
      • iOS:
        cd ios && rm -rf build && cd .. && npx react-native run-ios
      • Android:
        cd android && ./gradlew clean && cd .. && npx react-native run-android
  8. Chain sound configuration methods

    master

    The Sound instance allows you to chain non-getter calls to configure audio properties before playback. For example, you can set the volume and pan in a single chain followed by the play() command.

    sound.setVolume(.5).setPan(.5).play()
  9. Basic usage of react-native-sound

    master

    To play a sound, first enable playback in silence mode (essential for iOS) using Sound.setCategory('Playback'). Then, instantiate a new Sound object by providing the filename and the source type (e.g., Sound.MAIN_BUNDLE).

    Note: Always call release() on your sound instance when it is no longer needed to free up resources.

    import Sound from "react-native-sound";
    
    // Enable playback in silence mode (important for iOS)
    Sound.setCategory("Playback");
    
    // Load a sound file from the app bundle
    const whoosh = new Sound("whoosh.mp3", Sound.MAIN_BUNDLE, (error) => {
      if (error) {
        console.log("Failed to load the sound", error);
        return;
      }
    
      // Sound loaded successfully
      console.log("Duration:", whoosh.getDuration(), "seconds");
      console.log("Channels:", whoosh.getNumberOfChannels());
    
      // Play the sound
      whoosh.play((success) => {
        if (success) {
          console.log("Successfully finished playing");
        } else {
          console.log("Playback failed due to audio decoding errors");
        }
      });
    });
    
    // Audio controls
    whoosh.setVolume(0.5); // 50% volume
    whoosh.setPan(1); // Full right stereo
    whoosh.setNumberOfLoops(-1); // Loop indefinitely
    
    // Get current properties
    console.log("Volume:", whoosh.getVolume());
    console.log("Pan:", whoosh.getPan());
    console.log("Loops:", whoosh.getNumberOfLoops());
    
    // Seek to specific time
    whoosh.setCurrentTime(2.5);
    
    // Get current playback position
    whoosh.getCurrentTime((seconds) => {
      console.log("Current time:", seconds);
    });
    
    // Control playback
    whoosh.pause(); // Pause playback
    whoosh.stop(() => {
      // Stop and rewind
      whoosh.play(); // Play from beginning
    });
    
    // Always release resources when done
    whoosh.release();