UWP camera error: The stream number provided was invalid. PreviewState

UWP camera error: The stream number provided was invalid. PreviewState

我的 UWP 应用程序抛出 "UnhandledException" 消息:

The stream number provided was invalid. PreviewState.

应用程序执行 2 个操作:

这 2 个操作单独运行非常完美。

问题出现在我先"scan"(使用Zxing管理的相机预览),然后关闭"scan"预览,打开照片预览页面并旋转phone . "rotation" 导致异常。

我写了一个超级简单的应用程序来重现异常:

MainPage.xaml

<Button Content="Scan" Click="Scan_Click" />
<Button Content="Photo" Click="Photo_Click" />

MainPage.xaml.cs

    private async void Scan_Click(object sender, RoutedEventArgs e)
    {
        MobileBarcodeScanner scanner = new MobileBarcodeScanner();
        var result = await scanner.Scan();
    }

    private void Photo_Click(object sender, RoutedEventArgs e)
    {
        Frame.Navigate(typeof(PhotoPage));
    }

PhotoPage.xaml

<CaptureElement Name="PreviewControl" Stretch="Uniform"/>

PhotoPage.xaml.cs

    MediaCapture _mediaCapture;

    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        DeviceInformationCollection videoCaptureDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
        var camera = (from webcam in videoCaptureDevices
                      where webcam.EnclosureLocation != null
                      && webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
                      select webcam).FirstOrDefault();

        _mediaCapture = new MediaCapture();
        await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = camera.Id });
        PreviewControl.Source = _mediaCapture;
        await _mediaCapture.StartPreviewAsync();
    }

重现错误的步骤是:

谢谢!

我在 ZXing.Net.Mobile 问题页面上找到了解决方案: https://github.com/Redth/ZXing.Net.Mobile/issues/294

https://github.com/Redth/ZXing.Net.Mobile/blob/master/Source/ZXing.Net.Mobile.WindowsUniversal/ScanPage.xaml.cs 上发布的代码帮助我解决了问题。