react-native-sound-player icon indicating copy to clipboard operation
react-native-sound-player copied to clipboard

How can we change the speed of playback.

Open sudheerpal opened this issue 4 years ago • 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.

sudheerpal avatar Jan 15 '21 06:01 sudheerpal

Same issue

ngondat97 avatar May 03 '21 02:05 ngondat97

@johnsonsu please add function speed change

duongvtitleadpro avatar Jun 23 '21 04:06 duongvtitleadpro

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

AlkanV avatar Oct 12 '22 09:10 AlkanV

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

Robiullah2244 avatar Jun 27 '23 12:06 Robiullah2244

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.

Sneidon avatar Aug 25 '23 10:08 Sneidon