You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP中如何实现双摄像头预览或摄像头切换功能?

完全可行!既然你已经用过MediaCapture实现单摄像头预览,那扩展到双摄像头预览或切换功能其实是顺理成章的事儿,我给你梳理下具体的实现步骤:

实现UWP双摄像头预览/切换功能的方案

一、先获取所有可用的摄像头设备

要切换或同时使用多个摄像头,第一步得先枚举系统里的所有视频捕获设备。你可以用DeviceInformation.FindAllAsync筛选出摄像头设备,拿到每个设备的唯一ID,这是后续操作的核心:

// 获取系统中所有视频捕获设备
var allCameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
// 遍历设备,查看摄像头的ID和名称(方便用户选择)
foreach (var camera in allCameras)
{
    Debug.WriteLine($"摄像头ID: {camera.Id}, 名称: {camera.Name}");
}

二、实现摄像头切换功能

切换摄像头本质就是停止当前的预览会话,再用目标摄像头重新初始化MediaCapture:

  1. 先清理当前的MediaCapture实例:
if (_currentMediaCapture != null)
{
    await _currentMediaCapture.StopPreviewAsync();
    _currentMediaCapture.Dispose();
    _currentMediaCapture = null;
}
  1. 选择目标摄像头,重新初始化并启动预览:
// 假设你已经通过下拉菜单或其他方式选中了目标摄像头targetCamera
var initSettings = new MediaCaptureInitializationSettings
{
    VideoDeviceId = targetCamera.Id,
    StreamingCaptureMode = StreamingCaptureMode.Video // 仅启用视频预览
};

_currentMediaCapture = new MediaCapture();
await _currentMediaCapture.InitializeAsync(initSettings);
// 绑定到你的CaptureElement控件
previewControl.Source = _currentMediaCapture;
await _currentMediaCapture.StartPreviewAsync();

你可以做个下拉选择框,把所有摄像头的名称列出来,用户选择后触发上面的切换逻辑即可。

三、实现双摄像头同时预览

要同时显示两个摄像头的画面,需要创建两个独立的MediaCapture实例,分别绑定到两个CaptureElement控件:

  1. 先在XAML中添加两个预览控件:
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <!-- 左侧摄像头预览 -->
    <CaptureElement x:Name="LeftCameraPreview" Grid.Column="0"/>
    <!-- 右侧摄像头预览 -->
    <CaptureElement x:Name="RightCameraPreview" Grid.Column="1"/>
</Grid>
  1. 分别初始化两个MediaCapture实例:
var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (cameras.Count >= 2)
{
    // 初始化第一个摄像头
    var mediaCapture1 = new MediaCapture();
    await mediaCapture1.InitializeAsync(new MediaCaptureInitializationSettings
    {
        VideoDeviceId = cameras[0].Id,
        StreamingCaptureMode = StreamingCaptureMode.Video
    });
    LeftCameraPreview.Source = mediaCapture1;
    await mediaCapture1.StartPreviewAsync();

    // 初始化第二个摄像头
    var mediaCapture2 = new MediaCapture();
    await mediaCapture2.InitializeAsync(new MediaCaptureInitializationSettings
    {
        VideoDeviceId = cameras[1].Id,
        StreamingCaptureMode = StreamingCaptureMode.Video
    });
    RightCameraPreview.Source = mediaCapture2;
    await mediaCapture2.StartPreviewAsync();
}

⚠️ 注意:部分硬件可能存在限制,比如某些笔记本的集成摄像头和外接摄像头无法同时启用,测试时要留意这种情况。

四、关键注意事项

  • 权限声明:务必在Package.appxmanifest中添加webcam权限,否则应用无法访问摄像头设备。
  • 异常处理:初始化MediaCapture、启停预览时记得加try-catch,处理设备被占用、权限不足等异常场景。
  • 资源释放:退出页面或切换摄像头时,一定要正确释放MediaCapture实例,避免内存泄漏或设备占用问题。

内容的提问来源于stack exchange,提问作者Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:09:34