首页 > 解决方案 > 当我使用 expo 视频播放器将另一个视频推送到堆栈时,如何暂停或停止视频?

问题描述

当我使用 this.props.navigation.push 到导航堆栈时,我的视频继续在后台播放。有没有办法在我离开时暂停或停止视频?

<VideoPlayer
    videoProps={{
        shouldPlay: true,
        resizeMode: Video.RESIZE_MODE_CONTAIN,
        isMuted: false,
        source: {
            uri: this.props.navigation.state.params.video,
        },
    }}
    isPortrait
    playFromPositionMillis={0}
    showFullscreenButton
    switchToLandscape={() => 
        ScreenOrientation.allowAsync(ScreenOrientation.Orientation.LANDSCAPE)
    }
    switchToPortrait={() => 
        ScreenOrientation.allowAsync(ScreenOrientation.Orientation.PORTRAIT)
    }
/>

让我知道是否需要任何进一步的细节来澄清。

标签: react-nativereact-navigationexpo

解决方案


在您使用react-navigation时,您可以在导航生命周期事件上使用侦听器。https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

您可以订阅四个事件:

  • willFocus- 屏幕将聚焦
  • didFocus- 屏幕聚焦(如果有过渡,则过渡完成)
  • willBlur- 屏幕将不聚焦
  • didBlur- 屏幕失焦(如果有过渡,则过渡完成)

您可以根据需要订阅任意数量的内容。下面是一个使用的例子willBlur。您可以轻松地复制它来满足您的所有需求。

componentDidMount () {
  // add listener 
  this.willBlurSubscription = this.props.navigation.addListener('willBlur', this.willBlurAction);
}

componentWillUmount () {
  // remove listener
  this.willBlurSubscription.remove();
}

willBlurAction = (payload) => {
  // do things here when the screen blurs
}

VideoPlayer VideoPlayer 文档没有提供与Video 文档ref相同的功能,但您可以使用. 所以你可以做这样的事情:Video . _playbackInstance

<VideoPlayer 
 ref={ref => {this.videoplayer = ref}}
 // other props
/>

didBlurAction然后你可以在你的函数中做这样的事情

didBlurAction = (payload) => {
  if (this.videoplayer) {
    this.videoplayer._playbackInstance.pauseAsync();
  }
}

我制作了一种小吃来展示它的工作原理。在零食中,您可以在使用Video或之间切换VideoPlayer。当您导航到下一个屏幕时,视频会暂停。还有两个按钮可让您pauseplay视频。 https://snack.expo.io/@andypandy/video-example


推荐阅读