How can i pause or stop a video when i push anothe

2019-08-25 21:42发布

问题:

When I use this.props.navigation.push onto the navigation stack, my video continues to play in the background. Is there a way I can pause or stop the video as I navigate away?

<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)
    }
/>

Let me know if any further details are needed to clarify.

回答1:

As you are using react-navigation you can use listeners on the navigation lifecycle events. https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

There are four events you can subscribe to:

  • willFocus - the screen will focus
  • didFocus - the screen focused (if there was a transition, the transition completed)
  • willBlur - the screen will be unfocused
  • didBlur - the screen unfocused (if there was a transition, the transition completed)

You can subscribe to as many of them as you want. Here is an example of using willBlur. You could easily replicate this for all that you require.

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 does not expose the same ref functions that Video Video docs does, but you can get to them by using . _playbackInstance. So you could do something like this:

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

Then you could do something like this in your didBlurAction function

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

I have created a snack demonstrating it working. In the snack you are able to toggle between using Video or VideoPlayer. The video pauses when you navigate to the next screen. There are also two buttons allowing you to pause or play the video. https://snack.expo.io/@andypandy/video-example