MediaCapture StartPreviewAsync fails

2019-05-28 22:27发布

问题:

I am trying to start video preview capture from the camera in my UWP app but StartPreviewAsync throws an exception

Sample Code:

MediaCapture mc = new MediaCapture();
await mc.InitializeAsync();
await mc.StartPreviewAsync();

回答1:

This error occurs because currently StartPreviewAsync requires a sink to output frames to. This can be fixed by creating a capture element in xaml to display the frames.

<CaptureElement Name="captureElement"/>

now code can be updated to display the preview to the screen

MediaCapture mc = new MediaCapture();
await mc.InitializeAsync();
captureElement.Source = mc;
await mc.StartPreviewAsync();

If you want to start the preview without displaying anything to the screen you can create the captureElement in your app logic without adding to the view.

var captureElement = new CaptureElement();