johnsonsu/react-native-sound-player

How can we change the speed of playback.

Opened this issue · 6 comments

Is there any way where i can set the speed at which i want to play the audio. Right now 1x is default. I have some custom requirement where i should be able to increase or decrease the speed. Let's say 1.5X of original speed.

All views are invited.

Same issue

@johnsonsu please add function speed change

@johnsonsu hello John, is there any info about this one?

Hi @johnsonsu, please add the function to change the playback speed.

I have a workaround while we await the maintainer to implement this. The idea is to add the setSpeed method to the package and patch it so that the changes are not erased when you run npm install. It's a bit of a hassle, but here we go.

Go to your node_modules directory and update react-native-sound-player as follows:

  1. Add method to interface on index.d.ts (on root folder)
  setSpeed: (speed: number) => void;
  1. Ad method implementation on index.js (on root folder)
 setSpeed: (volume: number) => {
     RNSoundPlayer.setSpeed(volume);
 },
  1. Add method to RNSoundPlayer.m (on ios folder)
  RCT_EXPORT_METHOD(setVolume:(float) volume) {
    if (self.player != nil) {
        [self.player setVolume: volume];
    }
    if (self.avPlayer != nil) {
        [self.avPlayer setVolume: volume];
    }
  }
  1. Add and update theses methods on RNSoundPlayerModule.java (on android folder)
  • Add member variable
  private float speed = 1.0f;
  • Add new method
  @ReactMethod
  public void setSpeed(float speed) throws IOException {
    this.speed = speed;
    if (this.mediaPlayer != null) {
      this.mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed));
    }
  }
  • Update existing method
  @ReactMethod
  public void resume() throws IOException, IllegalStateException {
    if (this.mediaPlayer != null) {
      this.setVolume(this.volume);
      this.setSpeed(this.speed);
      this.mediaPlayer.start();
    }
  }

The method is now accessible using SoundPlayer.setSpeed(1.5). The final step is to patch the package to ensure that the changes persist after running npm install. To do this, follow these instructions:

  1. Install https://github.com/ds300/patch-package
  2. Run npx patch-package react-native-sound-player to patch your package

As you mentioned, this process can be a bit of a hassle, but it works if you're in a desperate situation.

+1 - I would also like to have this functionality