如何停止背景音乐播放? (反应本机声音)

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

我正在使用 react-native-sound 模块,但是当我启动声音并按下 Home 按钮退出应用程序时,声音一直在播放。

当我重新加载应用程序时,它会第二次启动声音,我无法在其上使用 .stop() 来销毁它,因为它只会销毁加载在第一个之上的第二个.

我该如何阻止它?

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);

我认为您应该使用 AppState 在后台停止音乐并在应用状态再次更改时启用音乐。

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();
  }
},

在 react-ative-sound 库中你只需要添加这一行

if (global.sound) global.sound.stop();

您可以在 backhandler 或 componentWillUnmount 中添加它。