如何停止后台音乐播放?(react-native-sound)

7
我正在使用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);

在活动的 onPause()onStop()onDestroy() 方法中调用 yourSound.stop() - Opiatefuchs
声音是我的应用程序的背景音乐。在第一页的componentWillReceiveProps()函数中使用mySound.play()进行调用。当重新加载应用程序时,它会在之前的背景音乐上再次开始另一首背景音乐。stop()函数不再起作用,好像无法检测到它。这就是为什么我试图避免在退出应用程序时恢复歌曲的原因。 - Sinan Samet
2个回答

8

我认为你应该使用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();
  }
},

0
在 react-ative-sound 库中,您只需要添加这一行代码。
if (global.sound) global.sound.stop();

您可以将此代码添加到backhandler或componentWillUnmount中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接