Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop music from playing in the background? (react-native-sound)

I am using the react-native-sound module but when I start a sound and I press the Home button to get out of the app, the sound keeps playing.

When I reload the app, it starts the sound a second time and I can't use .stop() on it to destroy it because it only destroys the second one which was loaded on top of the first one.

How am I supposed to stop that?

class Home extends Component {
  constructor(props) {
    super(props);
    this.props.actions.fetchScores();
  }

  componentWillReceiveProps(nextProps){
   nextProps.music.backgroundMusic.stop()

   setInterval( () => { 
    nextProps.music.backgroundMusic.play()
    nextProps.music.backgroundMusic.setNumberOfLoops(-1)
   }, 1000);
  }
}

export default connect(store => ({
    music: store.music
  })
)(Home);
like image 648
Sinan Samet Avatar asked Dec 04 '16 18:12

Sinan Samet


People also ask

How do I turn off background audio?

Open Control Center and tap the Hearing Devices button . Tap Background Sounds to turn it off.

Does Spotify use react native?

Events. This module uses react-native-events, so it has all of the same methods as an EventEmitter object. All of the events except for 'disconnect' / 'reconnect' (on Android) and 'login' / 'logout' come from Spotify's native SDK and are simply forwarded to javascript.

How do I turn off music in react native?

sound) global. sound. stop(); You can add this in backhandler or componentWillUnmount.


1 Answers

I think you should use AppState to stop music when in background and enable when app state changes again.

componentDidMount: function() {
  AppState.addEventListener('change', this._handleAppStateChange);
},
componentWillUnmount: function() {
  AppState.removeEventListener('change', this._handleAppStateChange);
},
_handleAppStateChange: function(currentAppState) {
  if(currentAppState == "background") {
      stop();
  } 
  if(currentAppState == "active") {
      resume();
  }
},
like image 164
coder hacker Avatar answered Sep 21 '22 02:09

coder hacker