react-native - 使用 StackNavigator 导航时取消音频
问题描述
我react-navigation-stack
在我的 React Native App 中使用。但是,在用户离开当前屏幕后继续播放音频时遇到问题。当用户导航到我的应用程序中的其他屏幕时,如何禁用音频?
我有一个 StackNavigator 设置如下:
//App.js
...
const MainNavigator = createStackNavigator({
Main: {screen: Main},
Song: {screen: Song},
SongList: {screen: SongList},
About: {screen: About}
})
...
屏幕Song
上有歌词和音频按钮。当用户单击音频按钮时,使用以下代码为他们播放音频:
//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”的addListener来检测用户何时离开屏幕(在其顶部打开另一个屏幕)并返回它。stop
或pause
声音模糊,resume
焦点。最后,release
声音(并移除听众)componentWillUnmount
添加示例
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()
})
}
})
}
}
推荐阅读
- javascript - 为什么 'google.script.run' 不能从 html body 'onload' 标签工作?
- memory - 对于计算程序,多少 RAM 才算太多?
- c - 设备驱动程序中“of_match_ptr()”的用途是什么
- php - Ajax 添加到购物车在 wordpress 5.6 中不起作用
- ruby-on-rails - 如何使按钮链接到 Rails 中的另一个 html 页面?
- python - 为什么我的战舰游戏代码会一遍又一遍地运行?
- python - Qt 设计器预览与 Python 中的实际 GUI 不同
- c# - 如何在 .NET 库类中记录应用程序洞察力?
- c# - 为什么 indexof 搜索文本不正确?
- r - 在双轴图表上重新标记一个轴