React-native-sound: Can't stop playing on componentWillUnmount

Created on 22 Nov 2017  路  5Comments  路  Source: zmxv/react-native-sound

A sample of the code that is causing the issue

class Home extends Component {
  playSound() {
    this.sound.play();
  }

  componentWillUnmount() {
    //gets called, but doesn't stop playing
    this.sound.stop();
    this.sound.release();
  }

  render(){
    this.sound = new Sound({ // sound source });
    return(
      <TouchableOpacity onPress={() => this.playSound()}>
        <View />
      </TouchableOpacity>
    );
  }
}

Most helpful comment

I have the same problem if I unmount the component BEFORE the sound is done preloading.
If I wait for the sound to start playing and then I unmount the component, the stop and release calls are working.

Have you found the solution yet??

All 5 comments

I have the same problem if I unmount the component BEFORE the sound is done preloading.
If I wait for the sound to start playing and then I unmount the component, the stop and release calls are working.

@kimulus I found out what went wrong and is different from your case.
What happened was that I created the sound instance in render(), and just right before the componentWillUnmount() is called, render() was called again, thus creating another sound instance. So this.sound was actually the new one that got created instead of the one that was used previously.

I have the same problem if I unmount the component BEFORE the sound is done preloading.
If I wait for the sound to start playing and then I unmount the component, the stop and release calls are working.

Have you found the solution yet??

I found a solution. You can useEffect of React Hooks as componentDidMount e componentWillUnmount in a single function.

  useEffect(() => {
    const playback = new Sound(audioSource, '', error => {
      if (error) {
        console.tron.log('failed to load the sound', error);
      }

      setDuration(playback.getDuration());
      console.tron.log('loaded successfully');
    });

    setFile(playback);

    return () => { // --> componentWillUnmount
      playback.stop();
      playback.release();
    };
  }, []);

It worked well for me. If you have a doubt, contact me.

I found a solution. You can useEffect of React Hooks as componentDidMount e componentWillUnmount in a single function.

  useEffect(() => {
    const playback = new Sound(audioSource, '', error => {
      if (error) {
        console.tron.log('failed to load the sound', error);
      }

      setDuration(playback.getDuration());
      console.tron.log('loaded successfully');
    });

    setFile(playback);

    return () => { // --> componentWillUnmount
      playback.stop();
      playback.release();
    };
  }, []);

It worked well for me. If you have a doubt, contact me.

Hi, i'm having simmilar issues, can you please help me?

Was this page helpful?
0 / 5 - 0 ratings