Android WebRTC应用退出画中画模式后本地SurfaceViewRenderer无预览如何处理
WebRTC Android 退出画中画模式本地预览恢复方案
远端用户可以正常接收你的相机流,说明视频采集逻辑、VideoTrack实例、上行传输链路均无异常,问题出在本地渲染链路:进入画中画模式时系统会销毁localVideoView绑定的Surface/SurfaceTexture,仅调用addLocalSink无法将渲染链路绑定到新的可用Surface,因此无法正常显示预览。
你需要补充执行以下操作恢复预览:
- 重新绑定
localVideoView的EGL上下文:如果你使用WebRTC官方的SurfaceViewRenderer作为预览控件,进入画中画后控件对应的Surface会被重建,需要重新调用init方法传入你全局持有的eglBaseContext,才能让控件具备渲染WebRTC视频帧的能力。 - 延迟到视图布局完成后添加sink:不要在画中画退出回调中直接调用
addLocalSink,此时localVideoView还未完成测量挂载,Surface处于不可用状态,需要在布局变更回调中触发sink添加逻辑。 - 进入画中画时主动移除sink:隐藏预览容器前先调用
videoTrack?.removeSink(localVideoView),避免VideoTrack向已销毁的Surface输出帧导致的底层异常。 - 确认视图可见性:父容器
localParticipantContainer恢复显示时,要保证子ViewlocalVideoView的visibility为VISIBLE,避免布局层级导致的渲染不可见。
示例代码实现
首先在LocalParticipant类中增加对外暴露eglBaseContext的方法:
// LocalParticipant.kt新增 fun getEglContext(): EglBase.Context = eglBaseContext
然后在宿主Activity中重写画中画模式切换回调:
override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) if (!isInPictureInPictureMode) { // 退出画中画,恢复本地预览 localParticipantContainer.visibility = View.VISIBLE // 重新初始化预览控件的EGL上下文 localVideoView.init(localParticipant.getEglContext(), null) // 等待布局完成后添加sink localVideoView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) { localVideoView.removeOnLayoutChangeListener(this) localParticipant.addLocalSink() } }) } else { // 进入画中画,清理无效渲染链路 localParticipant.videoTrack?.removeSink(localVideoView) localParticipantContainer.visibility = View.GONE } }
如果按照以上操作仍无法恢复预览,可以增加容错逻辑:在退出画中画时先调用videoCapturer?.stopCapture()再重新启动采集,不过该操作会导致远端流短暂中断,非必要不建议使用。
内容的提问来源于stack exchange,提问作者james04
相关产品推荐
相关产品推荐

