2016-12-04 194 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(); 
    } 
},