【问题标题】:How can i pause or stop a video when i push another video onto the stack using expo video player?当我使用 expo 视频播放器将另一个视频推送到堆栈时,如何暂停或停止视频?
【发布时间】:2019-02-09 08:55:23
【问题描述】:

当我使用 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-native react-navigation expo


    【解决方案1】:

    当您使用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 docs 不会提供与Video Video docs 相同的ref 函数,但您可以使用. _playbackInstance 来访问它们。所以你可以这样做:

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

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

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

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

    【讨论】:

    • 感谢您的快速回复。什么是'this.videoplayer',参考?传递给 didBlurAction 的有效载荷是什么?
    • this.videoplayer 是对您的 VideoPlayer 的引用。您可以在上面设置的代码中看到它。 payload 在函数中自动传递。您不必捕获或使用它。您可以通过链接reactnavigation.org/docs/en/… 了解更多信息
    • 通读文档,实现但我得到以下 typeerror subs is not a function。 (在 'subs(payloadWithType)' 中,'subs' 是未定义的,你之前有没有考虑过这个?
    • 我以前没有遇到过这个错误。但是,我已经更新了我的代码,因为我注意到其中有一个错误。我还为您制作了一种小吃供您尝试。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-02-03
    • 2019-11-18
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多