设置CaptureElement源null异常

时间:2018-11-07 18:22:23

标签: camera webcam mediacapture

我正在尝试进行一个简单的测试,以学习如何在Universal Windows项目(此后将在运行Windows 10 IoT核心的树莓派上使用)中一次设置和使用多个USB视频设备。我希望用户界面显示所选摄像机的预览。我已成功遵循MediaCapture网站HERE

上的预览示例

我有一个“ TakePicture”类,该类以后将用于其他用途,但目前用于查找和初始化连接到系统的视频设备,如下所示

public static class TakePicture
{
private static List<CaptureElement> _captureElements;
private static List<MediaCapture> _mediaCaptures;
public static DeviceInformationCollection devices;
private static int currentDevice = 0;

public static async Task InitializeDevice()
{
    if (currentDevice >= _captureElements.Count)
    {
        _mediaCaptures.Add(new MediaCapture());
        var captureElement = new CaptureElement{Stretch = Stretch.UniformToFill};
        _captureElements.Add(captureElement);
        await _mediaCaptures[currentDevice].InitializeAsync(
            new MediaCaptureInitializationSettings
            {
                VideoDeviceId = devices[currentDevice].Id,
                StreamingCaptureMode = StreamingCaptureMode.Video

            });
        _captureElements[currentDevice].Source = _mediaCaptures[currentDevice];
    }
}

public static void IncrimentDevice()
{

    currentDevice = (currentDevice + 1) % devices.Count;
}



public static async Task<MediaCapture> getPreviewElement()
{
    CaptureElement element = new CaptureElement();
    await FindDevices();
    await InitializeDevice();
    return _mediaCaptures[currentDevice];

}


public static async Task FindDevices()
{
    if (devices == null)
    {
        devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
        _captureElements = new List<CaptureElement>();
        _mediaCaptures = new List<MediaCapture>();
    }
}


}

我想返回一个与相机相关的MedaCapture对象,并使用该对象在GUI中如下设置CaptureElement的源:

private async Task StartPreviewAsync()
    {
        MediaCapture capture = await TakePicture.getPreviewElement();
        await capture.StartPreviewAsync();
        PreviewImage.Source = capture;
        PreviewImage.Visibility = Visibility.Visible;
    }

“ PreviewImage”是对UI中捕获元素的引用:

<CaptureElement Name="PreviewImage" Stretch="Uniform" HorizontalAlignment="Center" Height="649" Margin="0,84,0,0" VerticalAlignment="Top" Width="1147"/>

但是每次我尝试将源设置为MediaCapture元素时,都会得到一个空引用异常。我在调试器中检查了该对象是否不为null并具有已连接设备的ID,并且在运行

时更进一步
await capture.StartPreviewAsync(); 

相机下方的绿灯在相机上点亮。如果我尝试重新初始化GetPreviewElement返回的MediaCapture对象,则会引发设备也已经初始化的异常。

我要正确设置多个设备吗?是传递初始化的MediaCapture的副本是设置CaptureElement来源的有效方法吗?

非常感谢!

0 个答案:

没有答案