Flutter使用camera包录制视频时摄像头切换失败,求解决方案
解决方案
在录制视频状态下直接调用setDescription切换摄像头会触发相机资源冲突——当前录制流仍在占用原摄像头硬件,导致新摄像头无法正常初始化,最终出现黑屏后切回原摄像头的问题。针对这个情况,调整切换流程即可解决:
核心修复步骤
- 切换前停止当前录制任务,释放原摄像头占用
- 完成摄像头切换后,按需重新启动录制
修改后的代码示例
Future<void> switchCamera() async { if (cameraController != null) { // 检查录制状态,先停止录制 if (cameraController!.value.isRecordingVideo) { await cameraController!.stopRecording(); } final lensDirection = cameraController!.description.lensDirection; CameraDescription newDescription; if (lensDirection == CameraLensDirection.front) { newDescription = cameras.firstWhere((description) => description.lensDirection == CameraLensDirection.back); } else { newDescription = cameras.firstWhere((description) => description.lensDirection == CameraLensDirection.front); } // 执行摄像头切换 await cameraController!.setDescription(newDescription); // 如果需要自动恢复录制,取消下方注释 // await cameraController!.startRecording(); } else { await _initializeCameraController(_getDefaultCamera()); } }
进阶优化(避免异常)
如果cameras列表可能存在摄像头缺失的情况,建议给firstWhere添加兜底逻辑;若切换后预览仍有异常,可以尝试销毁原控制器后重新初始化:
Future<void> switchCamera() async { if (cameraController != null) { if (cameraController!.value.isRecordingVideo) { await cameraController!.stopRecording(); } // 释放原控制器资源 await cameraController!.dispose(); final currentLens = cameraController!.description.lensDirection; CameraDescription newCamera = cameraController!.description; // 默认保留当前摄像头 // 查找目标摄像头,添加兜底处理 if (currentLens == CameraLensDirection.front) { newCamera = cameras.firstWhere( (desc) => desc.lensDirection == CameraLensDirection.back, orElse: () => newCamera, ); } else { newCamera = cameras.firstWhere( (desc) => desc.lensDirection == CameraLensDirection.front, orElse: () => newCamera, ); } // 重新初始化摄像头控制器 cameraController = CameraController( newCamera, ResolutionPreset.high, // 根据业务需求调整分辨率 enableAudio: true, // 需录制音频则保持true ); await cameraController!.initialize(); // 按需恢复录制 // await cameraController!.startRecording(); } else { await _initializeCameraController(_getDefaultCamera()); } }
内容的提问来源于stack exchange,提问作者An Tran
相关产品推荐
相关产品推荐

