首页 > 解决方案 > 使用 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()
            })
        }
    })
}
...

如您所见,音频文件完成后会释放音频。但是,我如何设置它以便在用户离开当前页面时停止播放(被释放)?

标签: react-nativestack-navigator

解决方案


使用带有“didBlur”和“didFocus”的addListener来检测用户何时离开屏幕(在其顶部打开另一个屏幕)并返回它。stoppause声音模糊,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()
        })
      }
    })
  }
}

推荐阅读