Search code examples
c#uwpzxinguwp-xaml

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


My UWP application throw an "UnhandledException" with message:

The stream number provided was invalid. PreviewState.

The application do 2 operations:

  • take a photo (using MediaCapture and with preview in CaptureElement)
  • scan: read a QRcode (using Zxing.Net.Mobile)

The 2 operations works perfectly individually.

The problem appears when I first "scan" (with the preview from camera managed by Zxing), then close the "scan" preview, open the photo preview page and rotate the phone. The "rotation" cause the exception.

I wrote a super simple application to reproduce the exception:

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();
    }

The steps to reproduce the error are:

  • click Scan button
  • press "Back" phone button
  • click "Photo" button
  • rotate the phone

Thank you!


Solution

  • I've found a solution on a ZXing.Net.Mobile issue page: https://github.com/Redth/ZXing.Net.Mobile/issues/294

    The code posted at https://github.com/Redth/ZXing.Net.Mobile/blob/master/Source/ZXing.Net.Mobile.WindowsUniversal/ScanPage.xaml.cs help me resolve the problem.