React native 使用StackNavigator导航时取消音频
我正在我的react原生应用程序中使用React native 使用StackNavigator导航时取消音频,react-native,stack-navigator,React Native,Stack Navigator,我正在我的react原生应用程序中使用react导航堆栈。但是,在用户离开当前屏幕后,我仍然无法继续播放音频。当用户在我的应用程序中导航到其他屏幕时,我如何禁用音频 我的StackNavigator设置如下: //App.js ... const MainNavigator = createStackNavigator({ Main: {screen: Main}, Song: {screen: Song}, SongList: {screen: SongList},
react导航堆栈
。但是,在用户离开当前屏幕后,我仍然无法继续播放音频。当用户在我的应用程序中导航到其他屏幕时,我如何禁用音频
我的StackNavigator设置如下:
//App.js
...
const MainNavigator = createStackNavigator({
Main: {screen: Main},
Song: {screen: Song},
SongList: {screen: SongList},
About: {screen: About}
})
...
在歌曲
屏幕上有歌词和音频按钮。当用户单击音频按钮时,音频将使用以下代码为他们播放:
//Song.js
...
playAudio = (filepath) => {
var s = new Sound('audio/' + filepath, Sound.MAIN_BUNDLE, (error) => {
if (error){
console.log('error', error)
}
else {
s.play(()=>{
s.release()
})
}
})
}
...
正如您所见,音频文件完成后,音频将被释放。但是,如何设置它,使其在用户离开当前页面时停止播放(被释放?与“didBlur”和“didFocus”一起使用,以检测用户何时离开屏幕(在屏幕上方打开另一个屏幕)并返回屏幕<代码>停止或暂停
模糊声音,恢复
聚焦。最后,释放组件上的声音(并移除侦听器)将卸载
添加示例
class SongScreen extends React.Component {
componentDidMount() {
this.playAudio('some/filepath')
this.didBlurSubscription = this.props.navigation.addListener(
'didBlur',
() => this.sound.pause()
)
this.didFocusSubscription = this.props.navigation.addListener(
'didFocus',
() => this.sound.play()
)
}
componentWillUnmount() {
this.didBlurSubscription.remove()
this.didFocusSubscription.remove()
this.sound.stop().release()
}
playAudio = (filepath) => {
this.sound = new Sound('audio/' + filepath, Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('error', error)
} else {
this.sound.play(() => {
this.sound.release()
})
}
})
}
}
addListener到底会去哪里?在歌曲屏幕还是主屏幕?还有一个建议是,当你处理完侦听器后,删除它。我应该在哪里使用它呢?添加了一个例子@kojow7暂停工作确实需要几秒钟,这正常吗?不过现在它可以满足我的目的。嗯,如果我快速按两次后退箭头返回两个屏幕,那么它似乎不会调用暂停。我现在将didBlur
更改为willBlur
,它为我解决了这两个问题。