How to preview video from a webcam (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

You can preview live video from a camera or webcam by using a CaptureElement object and the Windows.Media.Capture API.

For another example of capturing media in a Windows Runtime app on both Windows and Windows Phone, see the Media capture sample. For an example of a full-featured camera app, recommended as a starting place for building your own camera app, see Advanced Camera Sample. This sample is currently only available for Windows Phone.

Roadmap: How does this topic relate to others? See:

Prerequisites

This topic assumes that you know how to create a basic Windows Runtime app using C++, C#, or Visual Basic. For help creating your first app, see Create your first Windows Store app using C# or Visual Basic.

Instructions

Step 1: Set the device capability in the app manifest

To enable webcam access, the app must include the **WebcamDeviceCapability in the application manifest.

  1. In Microsoft Visual Studio, in Solution Explorer, open the designer for the application manifest by double-clicking the package.appxmanifest item
  2. Click Capabilities.
  3. Check the box for Webcam.

Step 2: Create a CaptureElement to render video

Create a CaptureElement in Extensible Application Markup Language (XAML).You will use this to render the video to the display.

<CaptureElement Name="capturePreview" Height="400" />

Step 3: Create the MediaCapture object

The MediaCapture class contains methods and properties for managing the captured video. To capture video from a camera and preview it, you will need to use InitializeAsync and StartPreviewAsync.

This example instantiates a new MediaCapture object and calls InitializeAsync to initialize the MediaCapture object to the default settings. You can pass a MediaCaptureInitializationSettings object into InitializeAsync to set specific settings.

MediaCapture captureMgr = new MediaCapture();
await captureMgr.InitializeAsync();

Step 4: Start the video preview

The last thing to do is set the CaptureElement.Source to the MediaCapture object and start the preview using StartPreviewAsync.

// Start capture preview.
// capturePreview is a CaptureElement defined in XAML.
capturePreview.Source = captureMgr;

// Lock the display rotation before starting the preview.
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

await captureMgr.StartPreviewAsync();

Note that the rotation of the display is locked before starting the preview by setting the AutoRotationPreferences value. When you stop the preview, you can unlock the display rotation by setting the property to DisplayOrientations.None.

Step 5: Cleaning up MediaCapture resources properly

Warning  

It is extremely important that you properly shut down and dispose of the MediaCapture object and related objects when your app is suspended. Failure to do so could interfere with other apps accessing the device's camera which will result in a negative user experience for your app.

On Windows Phone, clean up your MediaCapture resources in the handler for the Suspending app lifetime event and recreate them in the Resuming event. On Windows, use the SoundLevelChanged events and check if sound level was muted. If it was muted, then clean up the MediaCapture resources. If the event indicates any other sound level, use the event to recreate them. Note that this event will not trigger your code even if you manually mute/unmute the sound while the app is running. So, this event effectively serves the same purpose as Suspend and Resume on phone. This is necessary because, on Windows, the user may be able to switch between apps without the current app being suspended.

 

You should cleanup media capture resources when your app in the Suspending event on Windows Phone or the SoundLevelChanged on Windows, as explained in the guidance in the above note. In order to do this, your App class will need to access your MediaCapture object and its current state. A good way to do this is to declare some public properties in your app.xaml.cs file to store the MediaCapture object, the CaptureElement you are using for your preview, and booleans that indicate whether the app is currently recording or previewing video.

public MediaCapture MediaCapture { get; set; }
public CaptureElement PreviewElement { get; set; }
public bool IsRecording { get; set; }
public bool IsPreviewing { get; set; }

Create a function in App.xaml.cs that stops recording or previewing if they are in progress. If you are using a MediaElement, set its source to null. And finally, call Dispose on your MediaCapture object.

public async Task CleanupCaptureResources()
{
    if (IsRecording && MediaCapture != null)
    {
        await MediaCapture.StopRecordAsync();
        IsRecording = false;
    }
    if (IsPreviewing && MediaCapture != null)
    {
        await MediaCapture.StopPreviewAsync();
        IsPreviewing = false;
    }

    if (MediaCapture != null)
    {
        if (PreviewElement != null)
        {
            PreviewElement.Source = null;
        }
        MediaCapture.Dispose();
    }
}

Finally, add the following code to your OnSuspending event handler. It is very important that you get a deferral before calling your cleanup method. This ensures that the system lets the method complete before suspending your app.

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();

    //cleanup camera resources
    await CleanupCaptureResources();

    deferral.Complete();
}

The full code for this example.

<CaptureElement Name="capturePreview" Height="400" />
MediaCapture captureMgr = new MediaCapture();
await captureMgr.InitializeAsync();

// Start capture preview.
// capturePreview is a CaptureElement defined in XAML.
capturePreview.Source = captureMgr;

// Lock the display rotation before starting the preview.
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;

await captureMgr.StartPreviewAsync();

Roadmaps

Roadmap for Windows Runtime apps using C# and Visual Basic

Roadmap for Windows Runtime apps using C++

Designing UX for apps

Adding multimedia

Samples

Media capture sample

Camera capture UI sample

Camera options UI sample

Device enumeration sample

Media extension sample

Real-Time communication sample

Tasks

Quickstart: video and audio

How to select audio tracks in different languages

Reference

Windows.Media.Capture

CaptureElement

Other resources

Supported audio and video formats

Optimize media resources