0

I want to use one TouchableOpacity for Play and Pause.

I am Using Audio from Firebase Server and react-native-sound to Play and Pause the Audio. Here is My Code:

constructor(props) {
    super(props)
    this.state = {
        isPlaying: true
    }
}
<TouchableOpacity
    onPress= {() => { 
        const { isPlaying } = this.state;
        var sound = new Sound(`${item.sound}`, null, (error)=> {
            if (isPlaying == false) {
                sound.play();
                this.setState({isPlaying:!isPlaying})
                console.warn("Played");

            } else if(isPlaying == true){
                sound.pause();
                this.setState({isPlaying:!isPlaying})
                console.warn("Paused");
            }
        })
    }
}
key={i}>Play</TouchableOpacity>

I am Able to Play the Sound but not able Pause.

I am New to react-native. Thanks in Advance.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

2 Answers2

2

Try this:

constructor(props) {
  super(props);
  this.state = {
    isPlaying: false
  }
  this.sound = new Sound();
}

startPlaying = () => {
  this.sound.play();
  this.setState({ isPlaying: true });
  console.warn("Now playing");
}

stopPlaying = () => {
  this.sound.pause();
  this.setState({ isPlaying: false })
  console.warn("Now paused");
}

onPlay(item) {
  const { isPlaying } = this.state;
  if(!isPlaying) {
    this.sound = new Sound(`${item.sound}`, null, this.startPlaying);
  } else {
    this.stopPlaying();
  }
}

<TouchableOpacity
   onPress={() => this.onPlay(item)}
   key={I}
>
   Play
</TouchableOpacity>
Konstantin Paulus
  • 1,943
  • 2
  • 10
  • 22
0

The problem is that you are creating new Sound instance on every Press, so when you call sound.pause() you are calling it on another Sound instance.

In your constructor or somewhere where you have access to item.sound, instantiate the Sound:

this.sound = new Sound(item.sound)

Your onPress callback should look like this:

    onPress= {() => {
     if(isPlaying) {
      this.sound.pause()
     } else {
      this.sound.play() 
    }
  }}
Stundji
  • 855
  • 7
  • 17