2016-12-04 190 views
1

我正在使用react-native-sound模块,但是当我启动声音并按Home按钮退出应用程序时,声音仍在播放。如何阻止音乐在后台播放? (react-native-sound)

当我重新加载应用程序时,它会再次启动声音,我不能使用.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); 
+0

调用'yourSound.stop()'活动'的onPause()','的onStop()'或'的onDestroy()'方法.. – Opiatefuchs

+0

声音是我的应用程序的backgroundmusic。它在第一页的'componentWillReceiveProps()'函数中用mySound.play()调用。当重新加载应用程序时,它将在前一个之上启动另一个背景音乐。 'stop()'函数不再工作,就好像它不能再检测到一样。这就是为什么我试图避免在离开应用程序时重新开始播放歌曲的原因。 –

回答

1

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