Selecting The Front Or Back Camera in Windows / Phone
I recently had a project where I needed a camera from a specific panel (the front-facing camera) in my Windows / Windows Phone app. It took me a little bit to track down all the information, so I thought I’d pull it all together here:
Make sure you add the Webcam and Microphone capabilities to your Package.appxmanifest or you’re get an Unauthorized Access Exception:
My XAML had a single CaptureElement to hold the video:
<CaptureElement x:Name=”CameraCaptureThingy” />
And I used the following code. The key here is line 5, where you enumerate which panel (front or back) has the camera you want to show video from.
var mediaCapture = new MediaCapture(); var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); var backCamera = videoDevices.FirstOrDefault( item => item.EnclosureLocation != null && item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back); MediaCapture mCapture = new MediaCapture(); if (backCamera != null) { var captureSettings = new MediaCaptureInitializationSettings { VideoDeviceId = backCamera.Id }; await mediaCapture.InitializeAsync(captureSettings); CameraCaptureThingy.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); }
This entry was posted in Windows Phone. Bookmark the permalink.
2 Responses to Selecting The Front Or Back Camera in Windows / Phone
Pingback: Dew Drop – January 7, 2015 (#1928) | Morning Dew
I’d like to share the method I use to switch cameras and respect rotation.
private async void SwitchCameras()
{
await mediaCaptureManager.StopPreviewAsync();
mediaCaptureManager.Dispose();
mediaCaptureManager = null;
mediaCaptureManager = new MediaCapture();
if (isUsingFrontCam)
{
await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = rearCamera.Id });
mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise90Degrees);
mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
}
else
{
await mediaCaptureManager.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = frontCamera.Id });
mediaCaptureManager.SetRecordRotation(VideoRotation.Clockwise270Degrees);
mediaCaptureManager.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
}
isUsingFrontCam = !isUsingFrontCam;
PreviewMediaElement.Source = mediaCaptureManager;
await mediaCaptureManager.StartPreviewAsync();
}