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:

appx amifest

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

2 thoughts on “Selecting The Front Or Back Camera in Windows / Phone

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

Comments are closed.