react-native - 当我使用 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-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
。当您导航到下一个屏幕时,视频会暂停。还有两个按钮可让您pause
或play
视频。
https://snack.expo.io/@andypandy/video-example
推荐阅读
- fortran - 将 openmp 共享变量添加到 fortran mpi 代码
- automation - 我们如何模拟空手道的内部 API 请求?
- java - Hibernate获取具有层次结构的双向关系的关联
- typescript - 如何扩展命名空间的接口
- node.js - npx - 在 `npx prettier` 与 `npx prettier@2` 中,`@` 做了什么?
- python - 从 Gmail 获取电子邮件并将其写入文件的最快方法
- reactjs - DataDog dd-trace-js 可以通过 http 标头向服务器发送跟踪信息吗?
- go - 无法使用 rm 命令从 Go 应用程序中删除 linux 服务器上的文件
- google-sheets - 使用间接函数创建循环过滤器 - Google 表格
- c# - Cefsharp 进程用户 ID 传递