javascriptreact-nativereact-native-sound

One Touchable Opacity for Play and Pause


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.


Solution

  • 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>