Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
MSDN Library
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

MediaCapture class

Provides functionality for capturing photos, audio, and videos from a capture device, such as a webcam.

Syntax


var mediaCapture = new Windows.Media.Capture.MediaCapture();

Members

The MediaCapture class has these types of members:

Constructors

The MediaCapture class has these constructors.

ConstructorDescription
MediaCapture Creates a new instance of the MediaCapture object.

 

Events

The MediaCapture class has these events.

EventDescription
CameraStreamStateChanged Occurs when the state of the camera stream changes.
Failed Raised when an error occurs during media capture.
FocusChanged Occurs when the capture device changes focus.
PhotoConfirmationCaptured Occurs when a photo confirmation frame is captured.
RecordLimitationExceeded Occurs when the record limit is exceeded.
ThermalStatusChanged Occurs when the thermal status of the capture device changes.

 

Methods

The MediaCapture class has these methods. With C#, Visual Basic, and C++, it also inherits methods from the Object class.

MethodDescription
AddAudioEffectAsync Adds an audio effect to the capture pipeline.
AddEffectAsync Adds an audio or video effect.
AddVideoEffectAsync Adds a video effect to the capture pipeline.
CapturePhotoToStorageFileAsync Captures a photo to a storage file.
CapturePhotoToStreamAsync Captures a photo to a random-access stream.
ClearEffectsAsync Removes all audio and video effects from a stream.
Close Closes the media capture object.
Close [C++, JavaScript]Closes the media capture object.
Dispose Performs tasks associated with freeing, releasing, or resetting unmanaged resources.
Dispose [C#, VB]Performs tasks associated with freeing, releasing, or resetting unmanaged resources.
FindAllVideoProfiles Retrieves the list of all video profiles supported by the specified video capture device.
FindConcurrentProfiles Retrieves the list of video profiles supported by the specified video capture device that can be used while another profile is used on a different capture device.
FindKnownVideoProfiles Retrieves the list of all video profiles supported by the specified video capture device that match the specified KnownVideoProfile value.
GetEncoderProperty Gets the value of an encoding property.
GetPreviewFrameAsync Gets a preview frame from the capture device.
GetPreviewFrameAsync(VideoFrame) Gets a preview frame from the capture device, copied into the provided destination VideoFrame and converted into the destination frame's format.
GetPreviewMirroring Queries whether the video stream is mirrored horizontally.
GetPreviewRotation Gets the rotation of the video preview stream.
GetRecordRotation Gets the rotation of the recorded video.
InitializeAsync Initializes the MediaCapture object, using default settings.
InitializeAsync(MediaCaptureInitializationSettings) Initializes the MediaCapture object.
IsVideoProfileSupported Gets a boolean value indicating whether video profiles are supported by the specified video capture device.
PauseRecordAsync Pauses an ongoing record operation.
PrepareAdvancedPhotoCaptureAsync Initializes the advanced photo capture and provides the AdvancedPhotoCapture object used to manage the recording.
PrepareLowLagPhotoCaptureAsync Initializes the low shutter lag photo capture and provides the LowLagPhotoCapture object used to manage the recording.
PrepareLowLagPhotoSequenceCaptureAsync Initializes the low shutter lag photo sequence capture and provides the LowLagPhotoSequenceCapture object used to manage the recording.
PrepareLowLagRecordToCustomSinkAsync(MediaEncodingProfile,IMediaExtension) Initializes the low lag recording using the specified custom sink to store the recording. This method provides the LowLagMediaRecording object used to managed the capture.
PrepareLowLagRecordToCustomSinkAsync(MediaEncodingProfile,String,IPropertySet) Initializes the low lag recording using the specified custom sink to store the recording. This method provides the LowLagMediaRecording object used to managed the recording.
PrepareLowLagRecordToStorageFileAsync Initializes the low lag recording using the specified file to store the recording. This method provides the LowLagMediaRecording object used to managed the recording.
PrepareLowLagRecordToStreamAsync Initializes the low lag recording using the specified random-access stream to store the recording. This method provides the LowLagMediaRecording object used to managed the recording.
PrepareVariablePhotoSequenceCaptureAsync Initializes the variable photo sequence capture and provides the VariablePhotoSequenceCapture object used to manage the recording.
ResumeRecordAsync Resumes a paused recording operation.
SetEncoderProperty Sets an encoding property.
SetEncodingPropertiesAsync Asynchronously sets the media encoding properties.
SetPreviewMirroring Enables or disables horizontal mirroring of the video preview stream.
SetPreviewRotation Rotates the video preview stream.
SetRecordRotation Rotates the recorded video.
StartPreviewAsync Starts preview.
StartPreviewToCustomSinkAsync(MediaEncodingProfile,IMediaExtension) Starts sending a preview stream to a custom media sink using the specified encoding profile.
StartPreviewToCustomSinkAsync(MediaEncodingProfile,String,IPropertySet) Starts sending a preview stream to a custom media sink using the specified encoding profile and sink settings.
StartRecordToCustomSinkAsync(MediaEncodingProfile,IMediaExtension) Start recording to a custom media sink using the specified encoding profile.
StartRecordToCustomSinkAsync(MediaEncodingProfile,String,IPropertySet) Start recording to a custom media sink using the specified encoding profile and sink settings.
StartRecordToStorageFileAsync Starts recording asynchronously to a storage file.
StartRecordToStreamAsync Starts recording to a random-access stream.
StopPreviewAsync Stops preview.
StopRecordAsync Stops recording.

 

Properties

The MediaCapture class has these properties.

PropertyAccess typeDescription

AudioDeviceController

Read-onlyGets an object that controls settings for the microphone.

CameraStreamState

Read-onlyGets the current stream state of the camera stream.

MediaCaptureSettings

Read-onlyGets the configuration settings for the MediaCapture object.

ThermalStatus

Read-onlyGets a value that indicates the current thermal status of the capture device.

VideoDeviceController

Read-onlyGets an object that controls settings for the video camera.

 

Remarks

The MediaCapture class is used to capture audio, video, and images from a camera. The InitializeAsync method, which initializes the capture device, must be called before you can start capturing from the device.

Use PrepareLowLagPhotoSequenceCaptureAsync to setup photo sequence mode, which takes a rapid sequence of photos. See the Media capture sample for an example of using photo sequence.

You can use the VideoDeviceController property to interact with the capture device. For example, you can use TorchControl and FlashControl properties to set the LED and flash on the device. Other properties on the VideoDeviceController are the SceneModeControl, RegionsOfInterestControl, FocusControl, and IsoSpeedControl. Each control provides a Supported property to determine if the device hardware supports the control.

In C# or C++ apps, the first use of the MediaCapture object to call InitializeAsync should be on the STA thread. Calls from an MTA thread may result in undefined behavior.

InitializeAsync will launch a consent prompt to get the user's permission for the app to access the microphone or camera. InitializeAsync should be called from the main UI thread of your app. For more information, see Guidelines for enabling sensitive devices.

If an app is previewing and it goes into a non-visible state, previewing should be stopped. If the app reenters a visible state, the MediaCapture needs to be recreated.

Note  On Windows, music and media capture apps should monitor the SystemMediaTransportControls.SoundLevel to determine whether the audio streams on the app have been Muted. For apps using the MediaCapture object, capture will be automatically stopped when the capture streams of the app are muted. Capture is not re-started automatically when the audio streams are unmuted, so the SoundLevel changed notification can be used to restart capture. Use the SystemMediaTransportControls.PropertyChanged event to determine when the SoundLevel property changes.

Note  For Windows Phone Store apps, music and media apps should clean up the MediaCapture object and associated resources in the Suspending event handler and recreate them in the Resuming event handler.

In Windows 8.1 audio only apps, if the MediaCategory setting is Other, then high latency mode is used. For low latency, set the MediaCategory setting to Communications.

Adding an in-place editing Media Foundation Transform effect into the capture preview will have no effect on the stream.

Windows 8 Windows Store apps that have declared both the webcam and microphone capabilities will not function in Windows 8.1 if the user has not enabled both the webcam and microphone privacy settings.

MediaCapture only supports one pass CBR encoding.

Notes on JPEG: JPEG types are passthrough only. To capture an image, the image encoding profile can be set to Auto or you need to specify an encoding profile that matches the native type. To add an effect, you need to switch to an uncompressed video native media type, such as NV12 or RGB32.

Notes on H.264: If the native type is H.264, you can record using a video media type with type identical to the native type. You cannot add an effect to an H.264 native type stream. To capture video, the image encoding profile can be set to Auto or you need to specify an encoding profile that matches the native type.

Note  : This class is not agile, which means that you need to consider its threading model and marshaling behavior. For more info, see Threading and Marshaling (C++/CX) and Using Windows Runtime objects in a multithreaded environment (.NET).
 

Examples

The following code sample shows how to create and initialize a MediaCapture object.


// Create and initialze the MediaCapture object.
function initMediaCapture() {
    oMediaCapture = null;
    oMediaCapture = new Windows.Media.Capture.MediaCapture();
    oMediaCapture.initializeAsync(captureInitSettings).then (function (result) {
       createProfile();
    }, errorHandler);    
}


Here is an example that shows how to preview a webcam using a CaptureElement and how to take a photo and display it in an Image object. The XAML creates a simple UI with a CaptureElement, Image, and some Button objects to interact with the MediaCapture element. In code, there is a method to initialize the MediaCapture object, a method to start previewing the camera attached to the MediaCapture object, a method to stop previewing, and a method to take a photo and display it.


<StackPanel Orientation="Horizontal">
    <CaptureElement x:Name="capturePreview" Width="320" Height="240" />
    <Image x:Name="imagePreivew" Stretch="None" Width="320" Height="240" />
</StackPanel>

<StackPanel Orientation="Horizontal">
    <Button Click="InitCamera_Click" Content="Initialize Camera" />
    <Button Click="StartCapturePreview_Click" Content="Start Capture Preview" />
    <Button Click="CapturePhoto_Click" Content="Capture Photo"/>
    <Button Click="StopCapturePreview_Click" Content="Stop Capture Preview" />
</StackPanel>



Windows.Media.Capture.MediaCapture captureManager;

async private void InitCamera_Click(object sender, RoutedEventArgs e)
{
    captureManager = new MediaCapture();
    await captureManager.InitializeAsync();
}

async private void StartCapturePreview_Click(object sender, RoutedEventArgs e)
{
    capturePreview.Source = captureManager;
    await captureManager.StartPreviewAsync();
}

async private void StopCapturePreview_Click(object sender, RoutedEventArgs e)
{
    await captureManager.StopPreviewAsync();
}

async private void CapturePhoto_Click(object sender, RoutedEventArgs e)
{
    ImageEncodingProperties imgFormat = ImageEncodingProperties.CreateJpeg();

    // create storage file in local app storage
    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        "TestPhoto.jpg",
        CreationCollisionOption.GenerateUniqueName);

    // take photo
    await captureManager.CapturePhotoToStorageFileAsync(imgFormat, file);

    // Get photo as a BitmapImage
    BitmapImage bmpImage = new BitmapImage(new Uri(file.Path));

    // imagePreivew is a <Image> object defined in XAML
    imagePreivew.Source = bmpImage;
}


See the Media Capture Sample for an example of using media capture.

If you’d like to try working with media capture and other key Windows 8 features, download the hands-on labs for Windows 8. These labs provide a modular, step-by-step introduction to creating a sample Windows Store app in the programming language of your choice (JavaScript and HTML or C# and XAML).

Requirements (Windows 10 device family)

Device family

Universal

API contract

Windows.Foundation.UniversalApiContract, introduced version 1.0

Namespace

Windows.Media.Capture
Windows::Media::Capture [C++]

Metadata

Windows.Foundation.UniversalApiContract.winmd

Capabilities

webcam
microphone

Requirements (Windows 8.x and Windows Phone 8.x)

Minimum supported client

Windows 8 [Windows Store apps, desktop apps]

Minimum supported server

Windows Server 2012 [Windows Store apps, desktop apps]

Minimum supported phone

Windows Phone 8.1 [Windows Phone Silverlight 8.1 and Windows Runtime apps]

Namespace

Windows.Media.Capture
Windows::Media::Capture [C++]

Metadata

Windows.winmd

Capabilities

webcam
microphone

Attributes

[DualApiPartition()]
[MarshalingBehavior(Standard)]
[Threading(MTA)]
[Version(0x06020000)]

See also

Object
IClosable
Guidelines for enabling sensitive devices
Roadmaps
Audio, video, and camera
Audio, video, and camera
Samples
Media capture sample
Camera capture UI sample
Camera options UI sample
Device enumeration sample
Real-Time communication sample
Media extension sample
Hands-on labs for Windows 8
Other resources
Supported audio and video formats

 

 

Show:
© 2015 Microsoft