MediaElement MediaElement MediaElement Class

Represents an object that renders audio and video to the display.

Use a MediaElement control to play audio and video files in your app. Built– in media transport controls let users interact with their media by providing a default playback experience comprised of various buttons including play, pause, closed captions, and others. See MediaTransportControls for more info.

Syntax

Declaration

public sealed class MediaElementpublic sealed class MediaElementPublic NotInheritable Class MediaElement
<MediaElement .../>

Inheritance Hierarchy

Inherited Members

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
Tag
Tag
Tag
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Remarks

For info about the media formats that MediaElement supports, see Supported codecs.

For info about performance related to MediaElement, see Optimize animations and media.

Set the media source

Set the Source property of the MediaElement object to point to an audio or video file. The property can be set to the Uniform Resource Identifier (URI) of a file that is included with the app or the Uniform Resource Identifier (URI) of a file on the network. You can use the SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String) method to set the source to a file retrieved from the local system by using a FileOpenPicker object.

By default, the media that is defined by the Source property plays immediately after the MediaElement object has loaded. To suppress the media from starting automatically, set the AutoPlay property to false.

Live media streams report a NaturalDuration of Int64.MaxValue.

Here's how to create a MediaElement in XAML with the Source set to the path of a video file that is included in the app and the AutoPlay property explicitly set to false.

<MediaElement Source="Media/video1.mp4" AutoPlay="false"/>

Here's how to create the MediaElement in code.

MediaElement mediaElement1 = new MediaElement();
mediaElement1.Source = new Uri("ms-appx:///Media/video1.mp4");
mediaElement1.AutoPlay = false;

// Add the MediaElement to the page.
rootGrid.Children.Add(mediaElement1);

Handle media events

You can respond to common media events such as the MediaOpened, MediaEnded, MediaFailed, and CurrentStateChanged events. It is good practice to always handle the MediaFailed event.

Transport controls

Set the AreTransportControlsEnabled property to programmatically enable and disable the built in transport controls for the MediaElement. The built in transport controls provide UI for playing, stopping, pausing, and seeking the media, as well as UI for volume, mute, full window, track selection, and remaining time.

You can create your own media transport controls by setting AreTransportControlsEnabled to false, and using the Play(), Pause(), and Stop() methods. MediaElement also exposes a rich set of properties you can control like Position, Volume, IsMuted, IsLooping, PlaybackRate, and Balance.

Tip

For better performance, avoid data binding to the Position property to reflect frequent position updates (for example with a progress bar). Instead, use the DispatcherTimer to query the Position property.

For more info and examples, see Create custom transport controls.

Open local media files

To open files on the local system or from Microsoft OneDrive, you can use the FileOpenPicker to get the file and SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String) to set the media source, or you can programmatically access the user media folders.

If your app needs access without user interaction to the Music or Video folders, for example if you are enumerating all the music or video files in the user's collection and displaying them in your app, then you need to declare the Music Library and Video Library capabilities. For more info, see Files and folders in the Music, Pictures, and Videos libraries.

The FileOpenPicker does not require special Capabilities to access files on the local file system, such as the user's Music or Video folders, since the user has complete control over which file is being accessed. From a security and privacy standpoint, it is best to minimize the number of capabilities your app uses.

To open local media using FileOpenPicker

    1. Call FileOpenPicker to let the user pick a media file.

Use the FileOpenPicker class to select a media file. Set the FileTypeFilter to specify which file types the FileOpenPicker will display. Call PickSingleFileAsync() to launch the file picker and get the file.

  1. Call SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String) to set the chosen media file as the Source.

To set the Source of the MediaElement to the StorageFile returned from the FileOpenPicker, you need to open a stream. Call the OpenAsync(Windows.Storage.FileAccessMode,Windows.Storage.StorageOpenOptions) method on the StorageFile returns a stream that you can pass into the SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String) method. Then call Play() on the MediaElement to start the media. This example shows how to use the FileOpenPicker to choose a file and set the file as the Source of a MediaElement.

<MediaElement x:Name="mediaPlayer"/>
...
<Button Content="Choose file" Click="Button_Click"/>
private async void Button_Click(object sender, RoutedEventArgs e)
{
    await SetLocalMedia();
}

async private System.Threading.Tasks.Task SetLocalMedia()
{
    var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

    openPicker.FileTypeFilter.Add(".wmv");
    openPicker.FileTypeFilter.Add(".mp4");
    openPicker.FileTypeFilter.Add(".wma");
    openPicker.FileTypeFilter.Add(".mp3");

    var file = await openPicker.PickSingleFileAsync();

    // mediaPlayer is a MediaElement defined in XAML
    if (file != null)
    {
        var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
        mediaPlayer.SetSource(stream, file.ContentType);

        mediaPlayer.Play();
    }
}

Select audio tracks in different languages

Use the AudioStreamIndex property and the GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32}) method to change the audio to a different language track on a video. Videos can also contain multiple audio tracks in the same language, such as director commentaries on films. This example specifically shows how to switch between different languages, but you can modify this code to switch between any audio tracks.

To select audio tracks in different languages

  1. Get the audio tracks.

To search for a track in a specific language, start by iterating through each audio track on the video. Use AudioStreamCount as the max value for a for loop.

  1. Get the language of the audio track.

Use the GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32}) method to get the language of the track. The language of the track is identified by a language code, such as "en" for English or "ja" for Japanese.

  1. Set the active audio track.

When you find the track with the desired language, set the AudioStreamIndex to the index of the track. Setting AudioStreamIndex to null selects the default audio track which is defined by the content. Here's some code that attempts to set the audio track to the specified language. It iterates through the audio tracks on a MediaElement object and uses GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32}) to get the language of each track. If the desired language track exists, the AudioStreamIndex is set to the index of that track.

/// <summary>
/// Attemps to set the audio track of a video to a specific language
/// </summary>
/// <param name="lcid">The id of the language. For example, "en" or "ja"</param>
/// <returns>true if the track was set; otherwise, false.</returns>
private bool SetAudioLanguage(string lcid, MediaElement media)
{
    bool wasLanguageSet = false;

    for (int index = 0; index < media.AudioStreamCount; index++)
    {
        if (media.GetAudioStreamLanguage(index) == lcid)
        {
            media.AudioStreamIndex = index;
            wasLanguageSet = true;
        }
    }

    return wasLanguageSet;
}

Full window playback

Use the IsFullWindow property to enable and disable full window rendering. When in full-window mode, input events received on the MediaElement will still route through to the visual tree in the background. For example, if the MediaElement is in a ListBox, turning the scroll wheel could cause the ListBox to scroll in the background. This can cause unexpected behavior. If input events should not be routed when in full-window mode, the MediaElement should handle the events.

Note

We recommend that you not use MediaElement in a Popup control. If a MediaElement hosted in a Popup is switched to full-window mode, the Popup is rendered on top of the MediaElement. If you must use a MediaElement in a Popup, you should collapse the Popup when the MediaElement enters full-window mode, and restore the Popup when the MediaElement exits full-window mode. Use RegisterPropertyChangedCallback(Windows.UI.Xaml.DependencyProperty,Windows.UI.Xaml.DependencyPropertyChangedCallback) to be notified when the IsFullWindow property changes. For an example, see the Examples section.

Keep media playing

To prevent the display from being deactivated when user action is no longer detected, such as when an app is playing video, you can call RequestActive(). To conserve power and battery life, you should call RequestRelease() to release the display request as soon as it is no longer required.

Here are some situations when you should release the display request:

  • Video playback is paused, for example by user action, buffering, or adjustment due to limited bandwidth.
  • Playback stops. For example, the video is done playing or the presentation is over.
  • A playback error has occurred. For example, network connectivity issues or a corrupted file. Here, you use the CurrentStateChanged event to detect these situations. Then, use the IsAudioOnly property to determine whether an audio or video file is playing, and keep the screen active only if video is playing.
<MediaElement Source="Media/video1.mp4"
              CurrentStateChanged="MediaElement_CurrentStateChanged"/>

// Create this variable at a global scope. Set it to null.
private DisplayRequest appDisplayRequest = null;

private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
    MediaElement mediaElement = sender as MediaElement;
    if (mediaElement != null && mediaElement.IsAudioOnly == false)
    {
        if (mediaElement.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
        {                
            if (appDisplayRequest == null)
            {
                // This call creates an instance of the DisplayRequest object. 
                appDisplayRequest = new DisplayRequest();
                appDisplayRequest.RequestActive();
            }
        }
        else // CurrentState is Buffering, Closed, Opening, Paused, or Stopped. 
        {
            if (appDisplayRequest != null)
            {
                // Deactivate the display request and set the var to null.
                appDisplayRequest.RequestRelease();
                appDisplayRequest = null;
            }
        }            
    }
}

Poster source

You can use the PosterSource property to provide your MediaElement with a visual representation before the media is loaded. A PosterSource is an image, such as a screen shot or movie poster, that is displayed in place of the media. The PosterSource is displayed in the following situations:

  • When a valid source is not set. For example, Source is not set, Source was set to Null, or the source is invalid (as is the case when a MediaFailed event fires).
  • While media is loading. For example, a valid source is set, but the MediaOpened event has not fired yet.
  • When media is streaming to another device.
  • When the media is audio only.

Notes for previous versions

Windows 8.1

On Windows Phone, you can only have one MediaElement at a time.

To let audio continue to play when your app is in the background, set the AudioCategory property to BackgroundCapableMedia. This also requires declaring the "Audio" background task capability in the app manifest. These values are deprecated in Windows 10.

Windows 8

Prior to Windows 8.1, the IsFullWindow property in not available. To enable full window video playback you must set the Width and Height of the MediaElement to the Bounds of the current window. Specifically, use Window.Current.Bounds.Width and Window.Current.Bounds.Height. Full window playback will not take advantage of system optimizations if you set the dimensions of a parent element, such as a grid, or a containing element instead of the MediaElement.

Prior to Windows 8.1, the Opacity property is not supported on MediaElement.

Prior to Windows 8.1, the AreTransportControlsEnabled property and built-in transport controls are not available. You must provide your own transport controls. For more info and examples, see Create custom transport controls and scenario 4 of the XAML media playback sample.

Windows Phone 8

Windows Phone Store app must use PickSingleFileAndContinue() to open local media files.

Examples

This code creates a MediaElement with the AutoPlay property explicitly set to true and the Source set to the path of a video file that is included in the app.

<MediaElement Source="Media/video1.mp4" AutoPlay="True" />
<MediaElement x:Name="mediaPlayer" 
              Source="Videos/video1.mp4" 
              Width="400" 
              AutoPlay="False"
              AreTransportControlsEnabled="True" />
<Grid>
    <Button Content="Show Popup" Click="ShowPopupClicked"/>
    <Popup x:Name="mediaPlayerPopup">
        <StackPanel Height="1400" Width="1400" Background="Blue">
            <MediaElement x:Name="mediaPlayer" 
                  AreTransportControlsEnabled="True" 
                  Source="Media/Intro.wmv"/>
            <TextBlock Text="Simple Popup"/>
            <Button Content="Close" Click="ClosePopupClicked"/>
        </StackPanel>
    </Popup>
</Grid>

long token;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    token = mediaPlayer.RegisterPropertyChangedCallback(MediaElement.IsFullWindowProperty, OnMEFullWindowChanged);
    base.OnNavigatedTo(e);
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    mediaPlayer.UnregisterPropertyChangedCallback(MediaElement.IsFullWindowProperty, token);
}

private void OnMEFullWindowChanged(DependencyObject sender, DependencyProperty dp)
{
    MediaElement me = (MediaElement)sender;

    if (me != null && dp == MediaElement.IsFullWindowProperty)
    {
        if (me.IsFullWindow == true)
        {
            mediaPlayerPopup.Visibility = Visibility.Collapsed;
        }
        else
        {
            mediaPlayerPopup.Visibility = Visibility.Visible;
        }
    }  
}

private void ClosePopupClicked(object sender, RoutedEventArgs e)
{
    // If the Popup is open, then close it.
    if (mediaPlayerPopup.IsOpen) { mediaPlayerPopup.IsOpen = false; }
}

// Handles the Click event on the Button on the page and opens the Popup. 
private void ShowPopupClicked(object sender, RoutedEventArgs e)
{
    // Open the Popup if it isn't open already. 
    if (!mediaPlayerPopup.IsOpen) { mediaPlayerPopup.IsOpen = true; }
}

Constructors summary

Instantiates a new instance of the MediaElement class.

Properties summary

Gets an enumeration value that determines the current value of stereo 3-D video frame-packing mode, accounting for other factors such as whether the media engine is ready for use.

Identifies the ActualStereo3DVideoPackingMode dependency property.

Gets or sets a value that determines whether the standard transport controls are enabled.

Identifies the AreTransportControlsEnabled dependency property.

Gets the height portion of the native aspect ratio of the media.

Identifies the AspectRatioHeight dependency property.

Gets the width portion of the native aspect ratio of the media.

Identifies the AspectRatioWidth dependency property.

Gets or sets a value that describes the purpose of the audio information in an audio stream.

Identifies the AudioCategory dependency property.

Gets or sets a value that describes the primary usage of the device that is being used to play back audio.

Identifies the AudioDeviceType dependency property.

Gets the number of audio streams that exist in the current media file.

Identifies the AudioStreamCount dependency property.

Gets or sets the index of the audio stream that plays along with the video component. The collection of audio streams is composed at run time and represents all audio streams that are available in the media file.

Identifies the AudioStreamIndex dependency property.

Gets or sets a value that indicates whether media will begin playback automatically when the Source property is set.

Identifies the AutoPlay dependency property.

Gets or sets a ratio of volume across stereo speakers.

Identifies the Balance dependency property.

Gets a value that indicates the current buffering progress.

Identifies the BufferingProgress dependency property.

Gets a value that indicates whether media can be paused if the Pause() method is called.

Identifies the CanPause dependency property.

Gets a value that indicates whether media can be repositioned by setting the value of the Position property.

Identifies the CanSeek dependency property.

Gets the status of this MediaElement.

Identifies the CurrentState dependency property.

Gets or sets the default playback rate for the media engine. The playback rate applies when the user isn't using fast forward or reverse.

Identifies the DefaultPlaybackRate dependency property.

Gets a value that indicates the amount of download completed for content located on a remote server.

Gets the offset of download progress, which is relevant in seek-ahead scenarios.

Identifies the DownloadProgressOffset dependency property.

Identifies the DownloadProgress dependency property.

Gets a value that reports whether the current source media is an audio-only media file.

Identifies the IsAudioOnly dependency property.

Gets a value that specifies if the MediaElement is rendering in full window mode. Setting this property enables or disables full window rendering.

Identifies the IsFullWindow dependency property.

Gets or sets a value that describes whether the media source currently loaded in the media engine should automatically set the position to the media start after reaching its end.

Identifies the IsLooping dependency property.

Gets or sets a value indicating whether the audio is muted.

Identifies the IsMuted dependency property.

Gets a value that reports whether the current source media is a stereo 3-D video media file.

Identifies the IsStereo3DVideo dependency property.

Gets the collection of timeline markers associated with the currently loaded media file.

Gets the duration of the media file currently opened.

Identifies the NaturalDuration dependency property.

Gets the height of the video associated with the media.

Identifies the NaturalVideoHeight dependency property.

Gets the width of the video associated with the media.

Identifies the NaturalVideoWidth dependency property.

Gets or sets the playback rate ratio for the media engine.

Identifies the PlaybackRate dependency property.

Gets or sets the path to the preferred media source which enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.

Identifies the PlayToPreferredSourceUri dependency property.

Gets the information that is transmitted if the MediaElement is used for a "PlayTo" scenario.

Identifies the PlayToSource dependency property.

Gets or sets the current position of progress through the media's playback time.

Identifies the Position dependency property.

Gets or sets the image source that is used for a placeholder image during MediaElement loading transition states.

Identifies the PosterSource dependency property.

Gets or sets the dedicated object for media content protection that is associated with this MediaElement.

Identifies the ProtectionManager dependency property.

Gets or sets a value that configures the MediaElement for real-time communications scenarios.

Identifies the RealTimePlayback dependency property.

Gets or sets a media source on the MediaElement.

Identifies the Source dependency property.

Gets or sets an enumeration value that determines the stereo 3-D video frame-packing mode for the current media source.

Identifies the Stereo3DVideoPackingMode dependency property.

Gets or sets an enumeration value that determines the stereo 3-D video render mode for the current media source.

Identifies the Stereo3DVideoRenderMode dependency property.

Gets or sets a value that describes how an MediaElement should be stretched to fill the destination rectangle.

Identifies the Stretch dependency property.

Gets or sets the transport controls for the media.

Gets or sets the media's volume.

Identifies the Volume dependency property.

Methods summary

Applies an audio effect to playback. Takes effect for the next source that is set on this MediaElement.

Applies a video effect to playback. Takes effect for the next source that is set on this MediaElement.

Returns an enumeration value that describes the likelihood that the current MediaElement and its client configuration can play that media source.

Returns the media element as a CastingSource.

Returns the RFC 1766 language for the specified audio stream.

Pauses media at the current position.

Plays media from the current position.

Removes all effects for the next source set for this MediaElement.

Sets the Source of the MediaElement to the specified SetMediaStreamSource(Windows.Media.Core.IMediaSource).

Sets the source of the MediaElement to the specified media playback source.

Sets the Source property using the specified stream and MIME type.

Stops and resets media to be played from the beginning.

Events summary

Occurs when the BufferingProgress property changes.

Occurs when the value of the CurrentState property changes.

Occurs when the DownloadProgress property has changed.

Occurs when a timeline marker is encountered during media playback.

Occurs when the MediaElement finishes playing audio or video.

Occurs when there is an error associated with the media Source.

Occurs when the media stream has been validated and opened, and the file headers have been read.

Occurs when one or more streams fails to decode in content containing multiple streams.

Occurs when PlaybackRate or DefaultPlaybackRate value changes.

Occurs when the seek point of a requested seek operation is ready for playback.

Occurs when the value of the Volume property changes.

Constructors

  • MediaElement()
    MediaElement()
    MediaElement()
    MediaElement()

    Instantiates a new instance of the MediaElement class.

    public MediaElement()public MediaElement()Public Function MediaElement() As

Properties

  • ActualStereo3DVideoPackingMode
    ActualStereo3DVideoPackingMode
    ActualStereo3DVideoPackingMode
    ActualStereo3DVideoPackingMode

    Gets an enumeration value that determines the current value of stereo 3-D video frame-packing mode, accounting for other factors such as whether the media engine is ready for use.

    public Stereo3DVideoPackingMode ActualStereo3DVideoPackingMode { get; }public Stereo3DVideoPackingMode ActualStereo3DVideoPackingMode { get; }Public ReadOnly Property ActualStereo3DVideoPackingMode As Stereo3DVideoPackingMode

    Property Value

    Remarks

    ActualStereo3DVideoPackingMode is used to determine the current Stereo3DVideoPackingMode being used by the subsystem. This could be different than what is set by the app author or if the app author sets None which is the default of Stereo3DVideoPackingMode.

  • ActualStereo3DVideoPackingModeProperty
    ActualStereo3DVideoPackingModeProperty
    ActualStereo3DVideoPackingModeProperty
    ActualStereo3DVideoPackingModeProperty

    Identifies the ActualStereo3DVideoPackingMode dependency property.

    public static DependencyProperty ActualStereo3DVideoPackingModeProperty { get; }public static DependencyProperty ActualStereo3DVideoPackingModeProperty { get; }Public Static ReadOnly Property ActualStereo3DVideoPackingModeProperty As DependencyProperty

    Property Value

  • AreTransportControlsEnabled
    AreTransportControlsEnabled
    AreTransportControlsEnabled
    AreTransportControlsEnabled

    Gets or sets a value that determines whether the standard transport controls are enabled.

    public bool AreTransportControlsEnabled { get; set; }public bool AreTransportControlsEnabled { get; set; }Public ReadWrite Property AreTransportControlsEnabled As bool
    <MediaElement AreTransportControlsEnabled="bool" />
    

    Property Value

    • bool
      bool
      bool

      true if the standard transport controls are enabled; otherwise, false. The default is false.

    Remarks

    The transport controls are exposed as a MediaTransportControls object that you can access through the TransportControls property. See MediaTransportControls for more info.

    If AreTransportControlsEnabled is true, the standard transport controls are enabled and displayed on the MediaElement. If AreTransportControlsEnabled is false, the standard transport controls are not enabled and are not displayed.

    The transport controls hide themselves after a short period of no user interaction with the MediaElement. They reappear when the user interacts with the MediaElement.

    If the Width of MediaElement is not sufficient to display all of the transport controls, a subset of the controls are displayed.

    Notes for previous versions

    Windows 8.1 You can't access and modify the built-in transport controls. If you create custom transport controls for your app, set this property to false to disable the built-in controls.

    Examples

    Here is some code that creates a MediaElement with the built-in transport controls enabled and the AutoPlay property set to false.

    <MediaElement x:Name="mediaPlayer" 
                  Source="Videos/video1.mp4" 
                  Width="400" 
                  AutoPlay="False"
                  AreTransportControlsEnabled="True" />
    
  • AreTransportControlsEnabledProperty
    AreTransportControlsEnabledProperty
    AreTransportControlsEnabledProperty
    AreTransportControlsEnabledProperty

    Identifies the AreTransportControlsEnabled dependency property.

    public static DependencyProperty AreTransportControlsEnabledProperty { get; }public static DependencyProperty AreTransportControlsEnabledProperty { get; }Public Static ReadOnly Property AreTransportControlsEnabledProperty As DependencyProperty

    Property Value

  • AspectRatioHeight
    AspectRatioHeight
    AspectRatioHeight
    AspectRatioHeight

    Gets the height portion of the native aspect ratio of the media.

    public int AspectRatioHeight { get; }public int AspectRatioHeight { get; }Public ReadOnly Property AspectRatioHeight As int

    Property Value

    • int
      int
      int

      The height portion of the native aspect ratio of the media. This value holds meaning only when you compare it with the value for the AspectRatioWidth property; the two properties together describe the aspect ratio.

  • AspectRatioHeightProperty
    AspectRatioHeightProperty
    AspectRatioHeightProperty
    AspectRatioHeightProperty

    Identifies the AspectRatioHeight dependency property.

    public static DependencyProperty AspectRatioHeightProperty { get; }public static DependencyProperty AspectRatioHeightProperty { get; }Public Static ReadOnly Property AspectRatioHeightProperty As DependencyProperty

    Property Value

  • AspectRatioWidth
    AspectRatioWidth
    AspectRatioWidth
    AspectRatioWidth

    Gets the width portion of the native aspect ratio of the media.

    public int AspectRatioWidth { get; }public int AspectRatioWidth { get; }Public ReadOnly Property AspectRatioWidth As int

    Property Value

    • int
      int
      int

      The width portion of the native aspect ratio of the media. This value holds meaning only when you compare it with the value for the AspectRatioHeight property; the two properties together describe the aspect ratio.

  • AspectRatioWidthProperty
    AspectRatioWidthProperty
    AspectRatioWidthProperty
    AspectRatioWidthProperty

    Identifies the AspectRatioWidth dependency property.

    public static DependencyProperty AspectRatioWidthProperty { get; }public static DependencyProperty AspectRatioWidthProperty { get; }Public Static ReadOnly Property AspectRatioWidthProperty As DependencyProperty

    Property Value

  • AudioCategory
    AudioCategory
    AudioCategory
    AudioCategory

    Gets or sets a value that describes the purpose of the audio information in an audio stream.

    public AudioCategory AudioCategory { get; set; }public AudioCategory AudioCategory { get; set; }Public ReadWrite Property AudioCategory As AudioCategory
    <MediaElement AudioCategory="audioCategoryMemberName" /.
    

    Property Value

    Remarks

    For hardware audio offload to be automatically applied, the audio category must be set to ForegroundOnlyMedia or BackgroundCapableMedia. Hardware audio offload optimizes audio rendering which can improve functionality and battery life.

  • AudioCategoryProperty
    AudioCategoryProperty
    AudioCategoryProperty
    AudioCategoryProperty

    Identifies the AudioCategory dependency property.

    public static DependencyProperty AudioCategoryProperty { get; }public static DependencyProperty AudioCategoryProperty { get; }Public Static ReadOnly Property AudioCategoryProperty As DependencyProperty

    Property Value

  • AudioDeviceType
    AudioDeviceType
    AudioDeviceType
    AudioDeviceType

    Gets or sets a value that describes the primary usage of the device that is being used to play back audio.

    public AudioDeviceType AudioDeviceType { get; set; }public AudioDeviceType AudioDeviceType { get; set; }Public ReadWrite Property AudioDeviceType As AudioDeviceType
    <MediaElement AudioDeviceType="audioDeviceTypeMemberName" /.
    

    Property Value

  • AudioDeviceTypeProperty
    AudioDeviceTypeProperty
    AudioDeviceTypeProperty
    AudioDeviceTypeProperty

    Identifies the AudioDeviceType dependency property.

    public static DependencyProperty AudioDeviceTypeProperty { get; }public static DependencyProperty AudioDeviceTypeProperty { get; }Public Static ReadOnly Property AudioDeviceTypeProperty As DependencyProperty

    Property Value

  • AudioStreamCount
    AudioStreamCount
    AudioStreamCount
    AudioStreamCount

    Gets the number of audio streams that exist in the current media file.

    public int AudioStreamCount { get; }public int AudioStreamCount { get; }Public ReadOnly Property AudioStreamCount As int

    Property Value

    • int
      int
      int

      The number of audio streams that exist in the source media file. The default value is 0.

  • AudioStreamCountProperty
    AudioStreamCountProperty
    AudioStreamCountProperty
    AudioStreamCountProperty

    Identifies the AudioStreamCount dependency property.

    public static DependencyProperty AudioStreamCountProperty { get; }public static DependencyProperty AudioStreamCountProperty { get; }Public Static ReadOnly Property AudioStreamCountProperty As DependencyProperty

    Property Value

  • AudioStreamIndex
    AudioStreamIndex
    AudioStreamIndex
    AudioStreamIndex

    Gets or sets the index of the audio stream that plays along with the video component. The collection of audio streams is composed at run time and represents all audio streams that are available in the media file.

    public IReference<int> AudioStreamIndex { get; set; }public IReference<int> AudioStreamIndex { get; set; }Public ReadWrite Property AudioStreamIndex As IReference<int>
    <MediaElement AudioStreamIndex="int"/>
    

    Property Value

    • The index in the media file of the audio component that plays along with the video component. The index can be unspecified, in which case the value is null. The default value is null.

      If you're programming using C#or Microsoft Visual Basic, the type of this property is projected as int?(a nullable integer).

    Remarks

    Setting AudioStreamIndex to null selects the default audio track, which is defined by the content.

  • AudioStreamIndexProperty
    AudioStreamIndexProperty
    AudioStreamIndexProperty
    AudioStreamIndexProperty

    Identifies the AudioStreamIndex dependency property.

    public static DependencyProperty AudioStreamIndexProperty { get; }public static DependencyProperty AudioStreamIndexProperty { get; }Public Static ReadOnly Property AudioStreamIndexProperty As DependencyProperty

    Property Value

  • AutoPlay
    AutoPlay
    AutoPlay
    AutoPlay

    Gets or sets a value that indicates whether media will begin playback automatically when the Source property is set.

    public bool AutoPlay { get; set; }public bool AutoPlay { get; set; }Public ReadWrite Property AutoPlay As bool
    <MediaElement AutoPlay="bool" .../>
    

    Property Value

    • bool
      bool
      bool

      true if playback is automatic; otherwise, false. The default is true.

  • AutoPlayProperty
    AutoPlayProperty
    AutoPlayProperty
    AutoPlayProperty

    Identifies the AutoPlay dependency property.

    public static DependencyProperty AutoPlayProperty { get; }public static DependencyProperty AutoPlayProperty { get; }Public Static ReadOnly Property AutoPlayProperty As DependencyProperty

    Property Value

  • Balance
    Balance
    Balance
    Balance

    Gets or sets a ratio of volume across stereo speakers.

    public double Balance { get; set; }public double Balance { get; set; }Public ReadWrite Property Balance As double
    <MediaElement Balance="double"  .../>
    

    Property Value

    • double
      double
      double

      The ratio of volume across speakers in the range between -1 and 1. The default value is 0.

  • BalanceProperty
    BalanceProperty
    BalanceProperty
    BalanceProperty

    Identifies the Balance dependency property.

    public static DependencyProperty BalanceProperty { get; }public static DependencyProperty BalanceProperty { get; }Public Static ReadOnly Property BalanceProperty As DependencyProperty

    Property Value

  • BufferingProgress
    BufferingProgress
    BufferingProgress
    BufferingProgress

    Gets a value that indicates the current buffering progress.

    public double BufferingProgress { get; }public double BufferingProgress { get; }Public ReadOnly Property BufferingProgress As double

    Property Value

    • double
      double
      double

      The amount of buffering that is completed for media content. The value ranges from 0 to 1. Multiply by 100 to obtain a percentage.

  • BufferingProgressProperty
    BufferingProgressProperty
    BufferingProgressProperty
    BufferingProgressProperty

    Identifies the BufferingProgress dependency property.

    public static DependencyProperty BufferingProgressProperty { get; }public static DependencyProperty BufferingProgressProperty { get; }Public Static ReadOnly Property BufferingProgressProperty As DependencyProperty

    Property Value

  • CanPause
    CanPause
    CanPause
    CanPause

    Gets a value that indicates whether media can be paused if the Pause() method is called.

    public bool CanPause { get; }public bool CanPause { get; }Public ReadOnly Property CanPause As bool

    Property Value

    • bool
      bool
      bool

      true if the media can be paused; otherwise, false.

  • CanPauseProperty
    CanPauseProperty
    CanPauseProperty
    CanPauseProperty

    Identifies the CanPause dependency property.

    public static DependencyProperty CanPauseProperty { get; }public static DependencyProperty CanPauseProperty { get; }Public Static ReadOnly Property CanPauseProperty As DependencyProperty

    Property Value

  • CanSeek
    CanSeek
    CanSeek
    CanSeek

    Gets a value that indicates whether media can be repositioned by setting the value of the Position property.

    public bool CanSeek { get; }public bool CanSeek { get; }Public ReadOnly Property CanSeek As bool

    Property Value

    • bool
      bool
      bool

      true if the media can be repositioned; otherwise, false.

  • CanSeekProperty
    CanSeekProperty
    CanSeekProperty
    CanSeekProperty

    Identifies the CanSeek dependency property.

    public static DependencyProperty CanSeekProperty { get; }public static DependencyProperty CanSeekProperty { get; }Public Static ReadOnly Property CanSeekProperty As DependencyProperty

    Property Value

  • CurrentState
    CurrentState
    CurrentState
    CurrentState

    Gets the status of this MediaElement.

    public MediaElementState CurrentState { get; }public MediaElementState CurrentState { get; }Public ReadOnly Property CurrentState As MediaElementState

    Property Value

    Remarks

    Examples

    The following example demonstrates one way to display the CurrentState of a MediaElement. It creates a MediaElement and several buttons for controlling media playback. To display the current state of the MediaElement, the example registers for the CurrentStateChanged event and uses an event handler to update a TextBlock.

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
    
        <MediaElement CurrentStateChanged="Media_State_Changed"
            x:Name="media" Source="xbox.wmv" Width="300" Height="300" 
                      Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="3" />
    
        <!-- Stops media playback.-->
        <Button Click="StopMedia" 
         Grid.Column="0" Grid.Row="1" Content="Stop" />
    
        <!-- Pauses media playback. -->
        <Button Click="PauseMedia" 
         Grid.Column="1" Grid.Row="1" Content="Pause" />
    
        <!-- Begins media playback. -->
        <Button Click="PlayMedia" 
         Grid.Column="2" Grid.Row="1" Content="Play" />
    
        <TextBlock
    Grid.Column="0" Grid.Row="2" Margin="10" 
    FontSize="12">CurrentState:</TextBlock>
    
        <TextBlock 
    x:Name="mediaStateTextBlock"
    Grid.Column="1" Grid.Row="2" Margin="0,10,0,0"
    FontSize="12"></TextBlock>
    
    </Grid>
    
    private void StopMedia(object sender, RoutedEventArgs e)
    {
        media.Stop();
    }
    private void PauseMedia(object sender, RoutedEventArgs e)
    {
        media.Pause();
    }
    private void PlayMedia(object sender, RoutedEventArgs e)
    {
        media.Play();
    }
    private void Media_State_Changed(object sender, RoutedEventArgs e)
    {
        mediaStateTextBlock.Text = media.CurrentState.ToString();
    }
    
    Private Sub StopMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
        media.Stop()
    End Sub
    
    Private Sub PauseMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
        media.Pause()
    End Sub
    
    Private Sub PlayMedia(ByVal sender As Object, ByVal e As RoutedEventArgs)
        media.Play()
    End Sub
    Private Sub Media_State_Changed(ByVal sender As Object, ByVal e As EventArgs)
        mediaStateTextBlock.Text = media.CurrentState.ToString
    End Sub
    
  • CurrentStateProperty
    CurrentStateProperty
    CurrentStateProperty
    CurrentStateProperty

    Identifies the CurrentState dependency property.

    public static DependencyProperty CurrentStateProperty { get; }public static DependencyProperty CurrentStateProperty { get; }Public Static ReadOnly Property CurrentStateProperty As DependencyProperty

    Property Value

  • DefaultPlaybackRate
    DefaultPlaybackRate
    DefaultPlaybackRate
    DefaultPlaybackRate

    Gets or sets the default playback rate for the media engine. The playback rate applies when the user isn't using fast forward or reverse.

    public double DefaultPlaybackRate { get; set; }public double DefaultPlaybackRate { get; set; }Public ReadWrite Property DefaultPlaybackRate As double
    <MediaElement DefaultPlaybackRate="double"/>
    

    Property Value

    • double
      double
      double

      The default playback rate. The default is 1.0, which indicates normal playback speed.

    Remarks

    The current PlaybackRate is set to the value of DefaultPlaybackRate whenever Play() is called. So setting DefaultPlaybackRate to a different value has no effect until Play() is called.

    To set a rate that will persist throughout the lifetime of the MediaElement, use DefaultPlaybackRate. Once playback ends, due to the MediaEnded event being raised or if Pause() or Stop() are called, the PlaybackRate will be effectively lost.

  • DefaultPlaybackRateProperty
    DefaultPlaybackRateProperty
    DefaultPlaybackRateProperty
    DefaultPlaybackRateProperty

    Identifies the DefaultPlaybackRate dependency property.

    public static DependencyProperty DefaultPlaybackRateProperty { get; }public static DependencyProperty DefaultPlaybackRateProperty { get; }Public Static ReadOnly Property DefaultPlaybackRateProperty As DependencyProperty

    Property Value

  • DownloadProgress
    DownloadProgress
    DownloadProgress
    DownloadProgress

    Gets a value that indicates the amount of download completed for content located on a remote server.

    public double DownloadProgress { get; }public double DownloadProgress { get; }Public ReadOnly Property DownloadProgress As double

    Property Value

    • double
      double
      double

      A value that indicates the amount of download completed for content that is located on a remote server. The value ranges from 0 to 1. Multiply by 100 to obtain a percentage.

  • DownloadProgressOffset
    DownloadProgressOffset
    DownloadProgressOffset
    DownloadProgressOffset

    Gets the offset of download progress, which is relevant in seek-ahead scenarios.

    public double DownloadProgressOffset { get; }public double DownloadProgressOffset { get; }Public ReadOnly Property DownloadProgressOffset As double

    Property Value

    • double
      double
      double

      The offset of download progress.

  • DownloadProgressOffsetProperty
    DownloadProgressOffsetProperty
    DownloadProgressOffsetProperty
    DownloadProgressOffsetProperty

    Identifies the DownloadProgressOffset dependency property.

    public static DependencyProperty DownloadProgressOffsetProperty { get; }public static DependencyProperty DownloadProgressOffsetProperty { get; }Public Static ReadOnly Property DownloadProgressOffsetProperty As DependencyProperty

    Property Value

  • DownloadProgressProperty
    DownloadProgressProperty
    DownloadProgressProperty
    DownloadProgressProperty

    Identifies the DownloadProgress dependency property.

    public static DependencyProperty DownloadProgressProperty { get; }public static DependencyProperty DownloadProgressProperty { get; }Public Static ReadOnly Property DownloadProgressProperty As DependencyProperty

    Property Value

  • IsAudioOnly
    IsAudioOnly
    IsAudioOnly
    IsAudioOnly

    Gets a value that reports whether the current source media is an audio-only media file.

    public bool IsAudioOnly { get; }public bool IsAudioOnly { get; }Public ReadOnly Property IsAudioOnly As bool

    Property Value

    • bool
      bool
      bool

      true if the current source media is audio-only, otherwise, false.

  • IsAudioOnlyProperty
    IsAudioOnlyProperty
    IsAudioOnlyProperty
    IsAudioOnlyProperty

    Identifies the IsAudioOnly dependency property.

    public static DependencyProperty IsAudioOnlyProperty { get; }public static DependencyProperty IsAudioOnlyProperty { get; }Public Static ReadOnly Property IsAudioOnlyProperty As DependencyProperty

    Property Value

  • IsFullWindow
    IsFullWindow
    IsFullWindow
    IsFullWindow

    Gets a value that specifies if the MediaElement is rendering in full window mode. Setting this property enables or disables full window rendering.

    public bool IsFullWindow { get; set; }public bool IsFullWindow { get; set; }Public ReadWrite Property IsFullWindow As bool
    <MediaElement IsFullWindow="bool" />
    

    Property Value

    • bool
      bool
      bool

      true if the MediaElement is in full window mode; otherwise, false. The default is false.

    Remarks

    Setting and un-setting this property enables and disables full window rendering.

    Always use the IsFullWindow property to enable and disable full window rendering. This ensures system level optimizations are used during media playback.

    When in full-window mode, input events received on the MediaElement will still route through to the visual tree in the background. For example, if the MediaElement is in a ListBox, turning the scroll wheel could cause the ListBox to scroll in the background. This can cause unexpected behavior. If input events should not be routed when in full-window mode, the MediaElement should handle the events.

  • IsFullWindowProperty
    IsFullWindowProperty
    IsFullWindowProperty
    IsFullWindowProperty

    Identifies the IsFullWindow dependency property.

    public static DependencyProperty IsFullWindowProperty { get; }public static DependencyProperty IsFullWindowProperty { get; }Public Static ReadOnly Property IsFullWindowProperty As DependencyProperty

    Property Value

  • IsLooping
    IsLooping
    IsLooping
    IsLooping

    Gets or sets a value that describes whether the media source currently loaded in the media engine should automatically set the position to the media start after reaching its end.

    public bool IsLooping { get; set; }public bool IsLooping { get; set; }Public ReadWrite Property IsLooping As bool
    <MediaElement IsLooping="bool"/>
    

    Property Value

    • bool
      bool
      bool

      true to loop the media and play continuously. false to not loop the media automatically. The default is false.

  • IsLoopingProperty
    IsLoopingProperty
    IsLoopingProperty
    IsLoopingProperty

    Identifies the IsLooping dependency property.

    public static DependencyProperty IsLoopingProperty { get; }public static DependencyProperty IsLoopingProperty { get; }Public Static ReadOnly Property IsLoopingProperty As DependencyProperty

    Property Value

  • IsMuted
    IsMuted
    IsMuted
    IsMuted

    Gets or sets a value indicating whether the audio is muted.

    public bool IsMuted { get; set; }public bool IsMuted { get; set; }Public ReadWrite Property IsMuted As bool
    <MediaElement IsMuted="bool" .../>
    

    Property Value

    • bool
      bool
      bool

      true if audio is muted; otherwise, false. The default is false.

  • IsMutedProperty
    IsMutedProperty
    IsMutedProperty
    IsMutedProperty

    Identifies the IsMuted dependency property.

    public static DependencyProperty IsMutedProperty { get; }public static DependencyProperty IsMutedProperty { get; }Public Static ReadOnly Property IsMutedProperty As DependencyProperty

    Property Value

  • IsStereo3DVideo
    IsStereo3DVideo
    IsStereo3DVideo
    IsStereo3DVideo

    Gets a value that reports whether the current source media is a stereo 3-D video media file.

    public bool IsStereo3DVideo { get; }public bool IsStereo3DVideo { get; }Public ReadOnly Property IsStereo3DVideo As bool

    Property Value

    • bool
      bool
      bool

      true if the current source media is stereo 3-D video, otherwise, false.

    Remarks

    If this property value is true, check Stereo3DVideoRenderMode for information on the render mode.

  • IsStereo3DVideoProperty
    IsStereo3DVideoProperty
    IsStereo3DVideoProperty
    IsStereo3DVideoProperty

    Identifies the IsStereo3DVideo dependency property.

    public static DependencyProperty IsStereo3DVideoProperty { get; }public static DependencyProperty IsStereo3DVideoProperty { get; }Public Static ReadOnly Property IsStereo3DVideoProperty As DependencyProperty

    Property Value

  • Markers
    Markers
    Markers
    Markers

    Gets the collection of timeline markers associated with the currently loaded media file.

    public TimelineMarkerCollection Markers { get; }public TimelineMarkerCollection Markers { get; }Public ReadOnly Property Markers As TimelineMarkerCollection

    Property Value

    Remarks

    A timeline marker is metadata associated with a particular point in a media file. These markers are usually created ahead of time and stored in the media file itself. They are typically used to name different scenes in a video or provide scripting cues. By handling the MediaElement object's MarkerReached event or by accessing the MediaElement object's Markers property, you can use timeline markers to trigger actions or enable users to seek to selected positions in the media file.

    Examples

    The following example creates a MediaElement object and responds to its MarkerReached event. Each time a timeline marker is reached, the example displays the timeline marker's Time, Type, and Text values.

    <MediaElement Name="Media" Source="video.mp4" MarkerReached="Media_MarkerReached" />
    <TextBlock Name="txOutput" />
    
    private void Media_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
    {
        txOutput.Text =
            string.Format("{0},{1},{2}", e.Marker.Time, e.Marker.Text, e.Marker.Type);
    }
    
  • NaturalDuration
    NaturalDuration
    NaturalDuration
    NaturalDuration

    Gets the duration of the media file currently opened.

    public Duration NaturalDuration { get; }public Duration NaturalDuration { get; }Public ReadOnly Property NaturalDuration As Duration

    Property Value

    Remarks

    A Duration value has a TimeSpan component.

    C# or Microsoft Visual Basic You can use utility methods of System.TimeSpan to get the duration components in whatever format you want. For example you can get TimeSpan.Hours, TimeSpan.Minutes and TimeSpan.Seconds separately.

    Visual C++ component extensions (C++/CX) The data value of a Duration is a property named TimeSpan. This has a TimeSpan structure value, and that structure has a field named Duration that reports the duration as an int64 that counts in 100-nanosecond units. TimeSpan doesn't have any methods for getting components of the time in hours:minutes:seconds format.

    For more info, see Remarks in the Duration reference topic.

  • NaturalDurationProperty
    NaturalDurationProperty
    NaturalDurationProperty
    NaturalDurationProperty

    Identifies the NaturalDuration dependency property.

    public static DependencyProperty NaturalDurationProperty { get; }public static DependencyProperty NaturalDurationProperty { get; }Public Static ReadOnly Property NaturalDurationProperty As DependencyProperty

    Property Value

  • NaturalVideoHeight
    NaturalVideoHeight
    NaturalVideoHeight
    NaturalVideoHeight

    Gets the height of the video associated with the media.

    public int NaturalVideoHeight { get; }public int NaturalVideoHeight { get; }Public ReadOnly Property NaturalVideoHeight As int

    Property Value

    • int
      int
      int

      The height of the video that is associated with the media, in pixels. Audio files return 0. The default is 0.

  • NaturalVideoHeightProperty
    NaturalVideoHeightProperty
    NaturalVideoHeightProperty
    NaturalVideoHeightProperty

    Identifies the NaturalVideoHeight dependency property.

    public static DependencyProperty NaturalVideoHeightProperty { get; }public static DependencyProperty NaturalVideoHeightProperty { get; }Public Static ReadOnly Property NaturalVideoHeightProperty As DependencyProperty

    Property Value

  • NaturalVideoWidth
    NaturalVideoWidth
    NaturalVideoWidth
    NaturalVideoWidth

    Gets the width of the video associated with the media.

    public int NaturalVideoWidth { get; }public int NaturalVideoWidth { get; }Public ReadOnly Property NaturalVideoWidth As int

    Property Value

    • int
      int
      int

      The width of the video associated with the media. The default is 0.

  • NaturalVideoWidthProperty
    NaturalVideoWidthProperty
    NaturalVideoWidthProperty
    NaturalVideoWidthProperty

    Identifies the NaturalVideoWidth dependency property.

    public static DependencyProperty NaturalVideoWidthProperty { get; }public static DependencyProperty NaturalVideoWidthProperty { get; }Public Static ReadOnly Property NaturalVideoWidthProperty As DependencyProperty

    Property Value

  • PlaybackRate
    PlaybackRate
    PlaybackRate
    PlaybackRate

    Gets or sets the playback rate ratio for the media engine.

    public double PlaybackRate { get; set; }public double PlaybackRate { get; set; }Public ReadWrite Property PlaybackRate As double
    <MediaElement PlaybackRate="double"/>
    

    Property Value

    • double
      double
      double

      The playback rate ratio for the media. A value of 1.0 is the normal playback speed. Value can be negative to play backwards.

    Remarks

    The current PlaybackRate is set to the value of DefaultPlaybackRate whenever Play() is called. So setting DefaultPlaybackRate to a different value has no effect until Play() is called.

    To set a rate that will persist throughout the lifetime of the MediaElement, use DefaultPlaybackRate. Once playback ends, due to the MediaEnded event being raised or if Pause() or Stop() are called, the PlaybackRate will be effectively lost.

  • PlaybackRateProperty
    PlaybackRateProperty
    PlaybackRateProperty
    PlaybackRateProperty

    Identifies the PlaybackRate dependency property.

    public static DependencyProperty PlaybackRateProperty { get; }public static DependencyProperty PlaybackRateProperty { get; }Public Static ReadOnly Property PlaybackRateProperty As DependencyProperty

    Property Value

  • PlayToPreferredSourceUri
    PlayToPreferredSourceUri
    PlayToPreferredSourceUri
    PlayToPreferredSourceUri

    Gets or sets the path to the preferred media source which enables the Play To target device to stream the media content, which can be DRM protected, from a different location, such as a cloud media server.

    public Uri PlayToPreferredSourceUri { get; set; }public Uri PlayToPreferredSourceUri { get; set; }Public ReadWrite Property PlayToPreferredSourceUri As Uri
    <MediaElement PlayToPreferredSourceUri="uri" />
    

    Property Value

    • The path to the preferred media source.

    Remarks

    PreferredSourceUri enables Play To by reference. This allows streaming content on the Play To target device from a different location, such as a cloud media server. This enables web pages and Windows Store app to play Digital Rights Management (DRM) protected content. The app specifies a preferred Uniform Resource Identifier (URI) that will be sent to the Play To target device. This Uniform Resource Identifier (URI) can point to a cloud based media server. If the PreferredSourceUri value is present, the Play To target device can stream content directly from the cloud, which can be Digital Rights Management (DRM) protected, instead of streaming content from the Windows machine which must be unprotected content.

    A forward slash ("/") is appended to the Uniform Resource Identifier (URI) string when it is sent over the network to a Play To device. This is done to conform to Uniform Resource Identifier (URI) standards.

    Examples

    Here is some code that shows how to set up Play To by reference.

    <MediaElement Source="http://www.contoso.com/videos/video.mp4" 
       PlayToPreferredSourceUri="http://www.contoso.com/catalogid=1234">
    </MediaElement>
    
    MediaElement video = new MediaElement();
    
    video.Source = 
        new Uri("http://www.contoso.com/videos/video.mp4");
    
    video.PlayToPreferredSourceUri = 
        new Uri("http://www.contoso.com/catalogid=1234");
    
    auto video = ref new Windows::UI::Xaml::Controls::MediaElement();
    
    video->Source = 
       ref new Windows::Foundation::Uri("http://www.contoso.com/videos/video.mp4");
    
    video->PlayToPreferredSourceUri = 
       ref new Windows::Foundation::Uri("http://www.contoso.com/catalogid=1234");
    
  • PlayToPreferredSourceUriProperty
    PlayToPreferredSourceUriProperty
    PlayToPreferredSourceUriProperty
    PlayToPreferredSourceUriProperty

    Identifies the PlayToPreferredSourceUri dependency property.

    public static DependencyProperty PlayToPreferredSourceUriProperty { get; }public static DependencyProperty PlayToPreferredSourceUriProperty { get; }Public Static ReadOnly Property PlayToPreferredSourceUriProperty As DependencyProperty

    Property Value

  • PlayToSource
    PlayToSource
    PlayToSource
    PlayToSource

    Gets the information that is transmitted if the MediaElement is used for a "PlayTo" scenario.

    public PlayToSource PlayToSource { get; }public PlayToSource PlayToSource { get; }Public ReadOnly Property PlayToSource As PlayToSource

    Property Value

  • PlayToSourceProperty
    PlayToSourceProperty
    PlayToSourceProperty
    PlayToSourceProperty

    Identifies the PlayToSource dependency property.

    public static DependencyProperty PlayToSourceProperty { get; }public static DependencyProperty PlayToSourceProperty { get; }Public Static ReadOnly Property PlayToSourceProperty As DependencyProperty

    Property Value

  • Position
    Position
    Position
    Position

    Gets or sets the current position of progress through the media's playback time.

    public TimeSpan Position { get; set; }public TimeSpan Position { get; set; }Public ReadWrite Property Position As TimeSpan

    Property Value

    • The amount of time since the beginning of the media. The default is a TimeSpan with value "0:0:0".

    Remarks

    Set this property to set a specific start-play position within the media.

    A TimeSpan is represented as different types depending on the programming language you are using.

    C# or Microsoft Visual Basic Use a System.TimeSpan structure. System.TimeSpan has utility members such as Parse(String) that make it easy to create, change or compare time values.

    Visual C++ component extensions (C++/CX) Use a TimeSpan structure. This structure has only one field member (Duration), which measures by 100-nanosecond units. If you intend to display a Position value in an hours:minutes:seconds format, you'll have to write your own logic for converting to that format from the Duration units.

    If you are not sure of the current media source loaded as Source, always check CanSeek first. A streaming media source results in the MediaElement reporting CanSeek as false, and in this case you cannot use Position to set the playback point.

    If Position is settable, then these value constraints apply:

    Notes on XAML syntax

    Setting a Position value in XAML is technically possible but not common. If you do set a Position in XAML, simulate the "FromString" type conversion behavior for a TimeSpan, in other words specify the value in the form "HH:MM:SS".

  • PositionProperty
    PositionProperty
    PositionProperty
    PositionProperty

    Identifies the Position dependency property.

    public static DependencyProperty PositionProperty { get; }public static DependencyProperty PositionProperty { get; }Public Static ReadOnly Property PositionProperty As DependencyProperty

    Property Value

  • PosterSource
    PosterSource
    PosterSource
    PosterSource

    Gets or sets the image source that is used for a placeholder image during MediaElement loading transition states.

    public ImageSource PosterSource { get; set; }public ImageSource PosterSource { get; set; }Public ReadWrite Property PosterSource As ImageSource
    <MediaElement PosterSource="imageUri" />
    

    Property Value

    Remarks

    A PosterSource is an image, such as a album cover or movie poster, that is displayed in place of video. It provides your MediaElement with a visual representation before the media is loaded, or when the media is audio only.

    The PosterSource is displayed in the following situations:

    • When a valid source is not set. For example, Source is not set, Source is set to Null, or the source is invalid (as is the case when a MediaFailed event fires).
    • While media is loading. For example, a valid source is set, but the MediaOpened event has not fired yet.
    • While media is streaming to another device.
    • When the media is audio only.
  • PosterSourceProperty
    PosterSourceProperty
    PosterSourceProperty
    PosterSourceProperty

    Identifies the PosterSource dependency property.

    public static DependencyProperty PosterSourceProperty { get; }public static DependencyProperty PosterSourceProperty { get; }Public Static ReadOnly Property PosterSourceProperty As DependencyProperty

    Property Value

  • ProtectionManager
    ProtectionManager
    ProtectionManager
    ProtectionManager

    Gets or sets the dedicated object for media content protection that is associated with this MediaElement.

    public MediaProtectionManager ProtectionManager { get; set; }public MediaProtectionManager ProtectionManager { get; set; }Public ReadWrite Property ProtectionManager As MediaProtectionManager

    Property Value

    Remarks

    See the PlayReady sample for for an example of using ProtectionManager.

  • ProtectionManagerProperty
    ProtectionManagerProperty
    ProtectionManagerProperty
    ProtectionManagerProperty

    Identifies the ProtectionManager dependency property.

    public static DependencyProperty ProtectionManagerProperty { get; }public static DependencyProperty ProtectionManagerProperty { get; }Public Static ReadOnly Property ProtectionManagerProperty As DependencyProperty

    Property Value

  • RealTimePlayback
    RealTimePlayback
    RealTimePlayback
    RealTimePlayback

    Gets or sets a value that configures the MediaElement for real-time communications scenarios.

    public bool RealTimePlayback { get; set; }public bool RealTimePlayback { get; set; }Public ReadWrite Property RealTimePlayback As bool
    <MediaElement RealTimePlayback="bool" />
    

    Property Value

    • bool
      bool
      bool

      true to configure for real-time communications. false to not configure the MediaElement for real-time communications.

    Remarks

    Configuring for real-time playback changes the internal update logic to place higher emphasis on video refresh from available samples, and also restricts playback to natural 1x speed. Setting the property requires an internal reconstruction of the backing media engine.

  • RealTimePlaybackProperty
    RealTimePlaybackProperty
    RealTimePlaybackProperty
    RealTimePlaybackProperty

    Identifies the RealTimePlayback dependency property.

    public static DependencyProperty RealTimePlaybackProperty { get; }public static DependencyProperty RealTimePlaybackProperty { get; }Public Static ReadOnly Property RealTimePlaybackProperty As DependencyProperty

    Property Value

  • Source
    Source
    Source
    Source

    Gets or sets a media source on the MediaElement.

    public Uri Source { get; set; }public Uri Source { get; set; }Public ReadWrite Property Source As Uri
    <MediaElement Source="uri" .../>
    

    Property Value

    • The source of the element, as an object describing a Uniform Resource Identifier (URI). The default is null.

  • SourceProperty
    SourceProperty
    SourceProperty
    SourceProperty

    Identifies the Source dependency property.

    public static DependencyProperty SourceProperty { get; }public static DependencyProperty SourceProperty { get; }Public Static ReadOnly Property SourceProperty As DependencyProperty

    Property Value

  • Stereo3DVideoPackingMode
    Stereo3DVideoPackingMode
    Stereo3DVideoPackingMode
    Stereo3DVideoPackingMode

    Gets or sets an enumeration value that determines the stereo 3-D video frame-packing mode for the current media source.

    public Stereo3DVideoPackingMode Stereo3DVideoPackingMode { get; set; }public Stereo3DVideoPackingMode Stereo3DVideoPackingMode { get; set; }Public ReadWrite Property Stereo3DVideoPackingMode As Stereo3DVideoPackingMode
    <MediaElement Stereo3DVideoPackingMode="stereo3DVideoPackingModeMemberName" .../>
    

    Property Value

    Remarks

    The Stereo3DVideoPackingMode default is to allow the system to determine the packing mode from the metadata of the video content. In order to reset a Stereo3DVideoPackingMode value once it has been set, use ClearValue(Windows.UI.Xaml.DependencyProperty). Stereo3DVideoPackingMode is used in conjunction with Stereo3DVideoRenderMode to display 3-D content.

    Examples

    <MediaElement x:Name="me1" Stereo3DVideoPackingMode="TopBottom" Stereo3DVideoRenderMode="Stereo"/>
    
  • Stereo3DVideoPackingModeProperty
    Stereo3DVideoPackingModeProperty
    Stereo3DVideoPackingModeProperty
    Stereo3DVideoPackingModeProperty

    Identifies the Stereo3DVideoPackingMode dependency property.

    public static DependencyProperty Stereo3DVideoPackingModeProperty { get; }public static DependencyProperty Stereo3DVideoPackingModeProperty { get; }Public Static ReadOnly Property Stereo3DVideoPackingModeProperty As DependencyProperty

    Property Value

  • Stereo3DVideoRenderMode
    Stereo3DVideoRenderMode
    Stereo3DVideoRenderMode
    Stereo3DVideoRenderMode

    Gets or sets an enumeration value that determines the stereo 3-D video render mode for the current media source.

    public Stereo3DVideoRenderMode Stereo3DVideoRenderMode { get; set; }public Stereo3DVideoRenderMode Stereo3DVideoRenderMode { get; set; }Public ReadWrite Property Stereo3DVideoRenderMode As Stereo3DVideoRenderMode
    <MediaElement Stereo3DVideoRenderMode="stereo3DVideoRenderModeMemberName" .../>
    

    Property Value

    Remarks

    IsStereo3DVideo is an evaluated read-only property that is based on Stereo3DVideoRenderMode.

    Set Stereo3DVideoRenderMode to Stereo3DVideoRenderMode when you want to enable the MediaElement to play 3D video. The API works in conjunction with Stereo3DVideoPackingMode, which lets you set the packing mode or allows the sub systems to infer it from the video file

    Examples

    <MediaElement x:Name="me1" Stereo3DVideoPackingMode="TopBottom" Stereo3DVideoRenderMode="Stereo"/>
    
  • Stereo3DVideoRenderModeProperty
    Stereo3DVideoRenderModeProperty
    Stereo3DVideoRenderModeProperty
    Stereo3DVideoRenderModeProperty

    Identifies the Stereo3DVideoRenderMode dependency property.

    public static DependencyProperty Stereo3DVideoRenderModeProperty { get; }public static DependencyProperty Stereo3DVideoRenderModeProperty { get; }Public Static ReadOnly Property Stereo3DVideoRenderModeProperty As DependencyProperty

    Property Value

  • Stretch
    Stretch
    Stretch
    Stretch

    Gets or sets a value that describes how an MediaElement should be stretched to fill the destination rectangle.

    public Stretch Stretch { get; set; }public Stretch Stretch { get; set; }Public ReadWrite Property Stretch As Stretch
    <MediaElement Stretch="stretchMemberName" />
    

    Property Value

    • A value of the Stretch enumeration that specifies how the source visual media is rendered. The default value is Uniform.

    Remarks

    Here's what the Stretch values represent for MediaElement content:

    • None: The original size of the content is preserved.
    • Fill: The content is resized to fill the destination dimensions. The aspect ratio of the video is not preserved.
    • UniformToFill: Uniformly stretches the MediaElement to fill the available layout space while preserving the aspect ratio of the content. If the aspect ratio of the destination rectangle differs from the source, the source content is clipped to fit the destination dimensions.
    • Uniform: Uniformly stretches the MediaElement to fill the layout space while preserve the aspect ratio of the image. This will ensure that the entire image is displayed, undistorted and not cropped. This may result in letterboxing or pillarboxing on the top or sides of the image, depending on the aspect ratio of the content.

    Examples

    Here is some code that shows how to create a zoom effect, similar to msZoom in Windows app using JavaScript. The MediaElement content will fill up the entire layout space while preserving the aspect ratio of the content. This could result in cropping if the aspect ratio of the content is not the same as the layout space.

    private void ToggleZoom(MediaElement media)
    {
        if (media.Stretch != Stretch.UniformToFill)
        {
            // zoom
            media.Stretch = Stretch.UniformToFill;
        }
        else
        {
            // unzoom
            media.Stretch = Stretch.Uniform;
        }
    }
    
  • StretchProperty
    StretchProperty
    StretchProperty
    StretchProperty

    Identifies the Stretch dependency property.

    public static DependencyProperty StretchProperty { get; }public static DependencyProperty StretchProperty { get; }Public Static ReadOnly Property StretchProperty As DependencyProperty

    Property Value

  • TransportControls
    TransportControls
    TransportControls
    TransportControls

    Gets or sets the transport controls for the media.

    public MediaTransportControls TransportControls { get; set; }public MediaTransportControls TransportControls { get; set; }Public ReadWrite Property TransportControls As MediaTransportControls

    Property Value

  • Volume
    Volume
    Volume
    Volume

    Gets or sets the media's volume.

    public double Volume { get; set; }public double Volume { get; set; }Public ReadWrite Property Volume As double
    <MediaElement Volume="double"/>
    

    Property Value

    • double
      double
      double

      The media's volume represented on a linear scale between 0 and 1. The default is 0.5.

  • VolumeProperty
    VolumeProperty
    VolumeProperty
    VolumeProperty

    Identifies the Volume dependency property.

    public static DependencyProperty VolumeProperty { get; }public static DependencyProperty VolumeProperty { get; }Public Static ReadOnly Property VolumeProperty As DependencyProperty

    Property Value

Methods

  • AddAudioEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddAudioEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddAudioEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddAudioEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)

    Applies an audio effect to playback. Takes effect for the next source that is set on this MediaElement.

    public void AddAudioEffect(System.String effectID,System.Boolean effectOptional,Windows.Foundation.Collections.IPropertySet effectConfiguration)public void AddAudioEffect(System.String effectID,System.Boolean effectOptional,Windows.Foundation.Collections.IPropertySet effectConfiguration)Public Function AddAudioEffect(effectID As System.String,effectOptional As System.Boolean,effectConfiguration As Windows.Foundation.Collections.IPropertySet) As void

    Parameters

    • effectID
      System.String
      System.String
      System.String

      The identifier for the desired effect.

    • effectOptional
      System.Boolean
      System.Boolean
      System.Boolean

      true if the effect shouldn't block playback when the effect can't be used at run time. false if the effect should block playback when the effect can't be used at run time.

    • effectConfiguration

      A property set that transmits property values to specific effects as selected by effectID.

    Remarks

    The audio effects needs to be added before loading the source. Otherwise, it will be applied for the next source that is set on this MediaElement.

  • AddVideoEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddVideoEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddVideoEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)
    AddVideoEffect(System.String,System.Boolean,Windows.Foundation.Collections.IPropertySet)

    Applies a video effect to playback. Takes effect for the next source that is set on this MediaElement.

    public void AddVideoEffect(System.String effectID,System.Boolean effectOptional,Windows.Foundation.Collections.IPropertySet effectConfiguration)public void AddVideoEffect(System.String effectID,System.Boolean effectOptional,Windows.Foundation.Collections.IPropertySet effectConfiguration)Public Function AddVideoEffect(effectID As System.String,effectOptional As System.Boolean,effectConfiguration As Windows.Foundation.Collections.IPropertySet) As void

    Parameters

    • effectID
      System.String
      System.String
      System.String

      The identifier for the desired effect.

    • effectOptional
      System.Boolean
      System.Boolean
      System.Boolean

      true if the effect shouldn't block playback when the effect can't be used at run time. false if the effect should block playback when the effect can't be used at run time.

    • effectConfiguration

      A property set that transmits property values to specific effects as selected by effectID.

  • CanPlayType(System.String)
    CanPlayType(System.String)
    CanPlayType(System.String)
    CanPlayType(System.String)

    Returns an enumeration value that describes the likelihood that the current MediaElement and its client configuration can play that media source.

    public MediaCanPlayResponse CanPlayType(System.String type)public MediaCanPlayResponse CanPlayType(System.String type)Public Function CanPlayType(type As System.String) As MediaCanPlayResponse

    Parameters

    • type
      System.String
      System.String
      System.String

      A string that describes the desired type as a MIME string.

    Returns

  • GetAsCastingSource()
    GetAsCastingSource()
    GetAsCastingSource()
    GetAsCastingSource()

    Returns the media element as a CastingSource.

    public CastingSource GetAsCastingSource()public CastingSource GetAsCastingSource()Public Function GetAsCastingSource() As CastingSource

    Returns

    Remarks

    For more info about using MediaElement as a casting source, see Media casting.

  • GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32})
    GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32})
    GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32})
    GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32})

    Returns the RFC 1766 language for the specified audio stream.

    public string GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32} index)public string GetAudioStreamLanguage(Windows.Foundation.IReference{System.Int32} index)Public Function GetAudioStreamLanguage(index As Windows.Foundation.IReference{System.Int32}) As string

    Parameters

    • index

      The index of the stream to get the language for.

      If you are programming using C#or Microsoft Visual Basic, the type of this parameter is projected as int?(a nullable integer).

    Returns

    • string
      string
      string

      The RFC 1766 language for the specified audio stream, expressed as a string (for example, "en-us").

  • Pause()
    Pause()
    Pause()
    Pause()

    Pauses media at the current position.

    public void Pause()public void Pause()Public Function Pause() As void
  • Play()
    Play()
    Play()
    Play()

    Plays media from the current position.

    public void Play()public void Play()Public Function Play() As void
  • RemoveAllEffects()
    RemoveAllEffects()
    RemoveAllEffects()
    RemoveAllEffects()

    Removes all effects for the next source set for this MediaElement.

    public void RemoveAllEffects()public void RemoveAllEffects()Public Function RemoveAllEffects() As void
  • SetMediaStreamSource(Windows.Media.Core.IMediaSource)
    SetMediaStreamSource(Windows.Media.Core.IMediaSource)
    SetMediaStreamSource(Windows.Media.Core.IMediaSource)
    SetMediaStreamSource(Windows.Media.Core.IMediaSource)

    Sets the Source of the MediaElement to the specified SetMediaStreamSource(Windows.Media.Core.IMediaSource).

    public void SetMediaStreamSource(Windows.Media.Core.IMediaSource source)public void SetMediaStreamSource(Windows.Media.Core.IMediaSource source)Public Function SetMediaStreamSource(source As Windows.Media.Core.IMediaSource) As void

    Parameters

  • SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource)
    SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource)
    SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource)
    SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource)

    Sets the source of the MediaElement to the specified media playback source.

    public void SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource source)public void SetPlaybackSource(Windows.Media.Playback.IMediaPlaybackSource source)Public Function SetPlaybackSource(source As Windows.Media.Playback.IMediaPlaybackSource) As void

    Parameters

  • SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String)
    SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String)
    SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String)
    SetSource(Windows.Storage.Streams.IRandomAccessStream,System.String)

    Sets the Source property using the specified stream and MIME type.

    public void SetSource(Windows.Storage.Streams.IRandomAccessStream stream,System.String mimeType)public void SetSource(Windows.Storage.Streams.IRandomAccessStream stream,System.String mimeType)Public Function SetSource(stream As Windows.Storage.Streams.IRandomAccessStream,mimeType As System.String) As void

    Parameters

    • stream

      The stream that contains the media to load.

    • mimeType
      System.String
      System.String
      System.String

      The MIME type of the media resource, expressed as the string form typically seen in HTTP headers and requests. The empty string "" can be passed in as the mimeType value if the MIME type is unknown.

    Remarks

    You can use the FileOpenPicker control to get the file stream for a media file on the local system.

    Examples

    Here is some code that creates MediaElement object and sets the media source using a FileOpenPicker control.

    <MediaElement x:Name="mediaControl" Height="400" />
    
    async private void SetLocalMedia()
    {
        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
    
        openPicker.FileTypeFilter.Add(".wmv");
        openPicker.FileTypeFilter.Add(".mp4");
        openPicker.FileTypeFilter.Add(".wma");
        openPicker.FileTypeFilter.Add(".mp3");
    
        var file = await openPicker.PickSingleFileAsync();
    
        // mediaControl is a MediaElement defined in XAML
        if (null != file)
        {
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
            mediaControl.SetSource(stream, file.ContentType);
            mediaControl.Play();
        }
    }
    
  • Stop()
    Stop()
    Stop()
    Stop()

    Stops and resets media to be played from the beginning.

    public void Stop()public void Stop()Public Function Stop() As void

Events

  • BufferingProgressChanged
    BufferingProgressChanged
    BufferingProgressChanged
    BufferingProgressChanged

    Occurs when the BufferingProgress property changes.

    public event RoutedEventHandler BufferingProgressChangedpublic event RoutedEventHandler BufferingProgressChangedPublic Event BufferingProgressChanged
    <MediaElement BufferingProgressChanged="eventhandler"/>
    
  • CurrentStateChanged
    CurrentStateChanged
    CurrentStateChanged
    CurrentStateChanged

    Occurs when the value of the CurrentState property changes.

    public event RoutedEventHandler CurrentStateChangedpublic event RoutedEventHandler CurrentStateChangedPublic Event CurrentStateChanged
    <MediaElement CurrentStateChanged="eventhandler"/>
    
  • DownloadProgressChanged
    DownloadProgressChanged
    DownloadProgressChanged
    DownloadProgressChanged

    Occurs when the DownloadProgress property has changed.

    public event RoutedEventHandler DownloadProgressChangedpublic event RoutedEventHandler DownloadProgressChangedPublic Event DownloadProgressChanged
    <MediaElement DownloadProgressChanged="eventhandler"/>
    
  • MarkerReached
    MarkerReached
    MarkerReached
    MarkerReached

    Occurs when a timeline marker is encountered during media playback.

    public event TimelineMarkerRoutedEventHandler MarkerReachedpublic event TimelineMarkerRoutedEventHandler MarkerReachedPublic Event MarkerReached
    <MediaElement MarkerReached="eventhandler"/>
    

    Remarks

    Examples

    The following example creates a MediaElement object and responds to its MarkerReached event. Each time a timeline marker is reached, the example displays the timeline marker's Time, Type, and Text values.

    <MediaElement Name="Media" Source="video.mp4" MarkerReached="Media_MarkerReached" />
    <TextBlock Name="txOutput" />
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Media;
    using Windows.Media.Capture;
    using Windows.Media.Transcoding;
    using Windows.Graphics.Display;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace MediaXamlSnippets
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            /// <summary>
            /// Invoked when this page is about to be displayed in a Frame.
            /// </summary>
            /// <param name="e">Event data that describes how this page was reached.  The Parameter
            /// property is typically used to configure the page.</param>
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
    
            private void btnStart_Click_1(object sender, RoutedEventArgs e)
            {
                media.Play();
            }
    
            private void btnStop_Click_1(object sender, RoutedEventArgs e)
            {
                media.Stop();
            }
    
            private void ChangeAudio(object sender, RoutedEventArgs e)
            {
                SetAudioLanguage("ja", media);
            }
    
            // <SnippetPlaybackAudioTracks>
            /// <summary>
            /// Attemps to set the audio track of a video to a specific language
            /// </summary>
            /// <param name="lcid">The id of the language. For example, "en" or "ja"</param>
            /// <returns>true if the track was set; otherwise, false.</returns>
            private bool SetAudioLanguage(string lcid, MediaElement media)
            {
                bool wasLanguageSet = false;
    
                for (int index = 0; index < media.AudioStreamCount; index++)
                {
                    if (media.GetAudioStreamLanguage(index) == lcid)
                    {
                        media.AudioStreamIndex = index;
                        wasLanguageSet = true;
                    }
                }
    
                return wasLanguageSet;
            }
            // </SnippetPlaybackAudioTracks>
    
            private void btnRealTime_Click_1(object sender, RoutedEventArgs e)
            {
                // <SnippetPlaybackRealTime>
                MediaElement media = new MediaElement();
                media.RealTimePlayback = true;
                // </SnippetPlaybackRealTime>
            }
    
            Windows.Media.Capture.MediaCapture captureMgr;
    
            async void InitCapture()
            {
                captureMgr = new Windows.Media.Capture.MediaCapture();
    
                await captureMgr.InitializeAsync();
    
                capturePreview.Source = captureMgr;
    
                await captureMgr.StartPreviewAsync();
    
            }
    
            private void btCapture_Click_1(object sender, RoutedEventArgs e)
            {
                InitCapture();
            }
    
    
            private void btnCaptureRotate_Click(object sender, RoutedEventArgs e)
            {
                CaptureAndRotate(captureMgr);
            }
    
            async void CaptureAndRotate(MediaCapture captureMgrReal)
            {
                // <SnippetCaptureRotateAll>
                // <SnippetCaptureRotateInit>
                MediaCapture captureMgr = new MediaCapture();
    
                // Set the MediaCapture to a variable in App.xaml.cs to handle suspension.
                (App.Current as App).MediaCapture = captureMgr;
    
                await captureMgr.InitializeAsync();
                // </SnippetCaptureRotateInit>
    
                // <SnippetCaptureRotateSetRotate>
                captureMgr.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                // </SnippetCaptureRotateSetRotate>
    
                // <SnippetCaptureRotateGetRotate>
                VideoRotation previewRotation = captureMgr.GetPreviewRotation();
                // </SnippetCaptureRotateGetRotate>
    
                // Start capture preview.
                // capturePreview is a CaptureElement defined in XAML.
                capturePreview.Source = captureMgr;
    
                // Set the CaptureElement to a variable in App.xaml.cs to handle suspension.
                (App.Current as App).PreviewElement = capturePreview;
    
                // Lock the orientation of the display while previewing.
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
    
                await captureMgr.StartPreviewAsync();
    
                // Set a tracking variable for preview state in App.xaml.cs
                (App.Current as App).IsPreviewing = true;
                // </SnippetCaptureRotateAll>    
            }
    
            async void RecordAndRotate(MediaCapture captureMgr)
            {
                captureMgr = new MediaCapture();
                await captureMgr.InitializeAsync();
    
                // <SnippetCaptureRotateSetRecordRotate>
                //captureMgr.SetRecordRotation(VideoRotation.Clockwise90Degrees);
                // </SnippetCaptureRotateSetRecordRotate>
    
                capturePreview.Source = captureMgr;
                await captureMgr.StartPreviewAsync();
            }
            //<SnippetStartRecordWithRotation>
            public async void StartRecordWithRotation(Windows.Storage.StorageFile videoFile)
            {
    
                var mediaEncodingProps = Windows.Media.MediaProperties.MediaEncodingProfile.CreateMp4(
                    Windows.Media.MediaProperties.VideoEncodingQuality.Auto);
    
                System.Guid MFVideoRotationGuid =
                new System.Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"); // MF_MT_VIDEO_ROTATION in Mfapi.h
    
                int MFVideoRotation = ConvertVideoRotationToMFRotation(VideoRotation.Clockwise90Degrees);
    
                mediaEncodingProps.Video.Properties.Add(MFVideoRotationGuid, PropertyValue.CreateInt32(MFVideoRotation));
    
                await captureMgr.StartRecordToStorageFileAsync(mediaEncodingProps, videoFile);
            }
     
            int ConvertVideoRotationToMFRotation(VideoRotation rotation)
            {
                int MFVideoRotation = 0; // MFVideoRotationFormat::MFVideoRotationFormat_0 in Mfapi.h
                switch(rotation)
                {
                case VideoRotation.Clockwise90Degrees:
                    MFVideoRotation = 90; // MFVideoRotationFormat::MFVideoRotationFormat_90;
                    break;
                case VideoRotation.Clockwise180Degrees:
                    MFVideoRotation = 180; // MFVideoRotationFormat::MFVideoRotationFormat_180;
                    break;
                case VideoRotation.Clockwise270Degrees:
                    MFVideoRotation = 270; // MFVideoRotationFormat::MFVideoRotationFormat_270;
                    break;
                }
     
                return MFVideoRotation;
            }
            //</SnippetStartRecordWithRotation>
    
    
            async void AddEffectCapture(MediaCapture captureMgrReal)
            {
                // <SnippetCaptureAddEffect>
                MediaCapture captureMgr = new MediaCapture();
                await captureMgr.InitializeAsync();
    
                await captureMgr.AddEffectAsync(
                    MediaStreamType.VideoRecord,
                    Windows.Media.VideoEffects.VideoStabilization,
                    null);
                // </SnippetCaptureAddEffect>
    
                // For Testing snippet.  Don't include in snippet.
                captureMgrReal = captureMgr;
                capturePreview.Source = captureMgrReal;
                await captureMgr.StartPreviewAsync();
    
                // <SnippetCaptureRemoveEffect>
                // captureMgr is of type MediaCapture.
                await captureMgr.ClearEffectsAsync(MediaStreamType.VideoRecord);
                // </SnippetCaptureRemoveEffect>
            }
    
            private void AddTranscoderEffect()
            {
                // <SnippetTranscodingAddEffect>
                MediaTranscoder transcoder = new MediaTranscoder();
    
                transcoder.AddVideoEffect(
                    "Windows.Media.VideoEffects.VideoStabilization");
                // </SnippetTranscodingAddEffect>
    
                // <SnippetTranscodingRemoveEffect>
                transcoder.ClearEffects();
                // </SnippetTranscodingRemoveEffect>
    
            }
    
            async void ClearEffectsCapture(MediaCapture captureMgr)
            {
                await captureMgr.ClearEffectsAsync(MediaStreamType.VideoRecord);
            }
    
            private void btnRotate_Click_1(object sender, RoutedEventArgs e)
            {
                if (captureMgr != null)
                {
                    if (captureMgr.GetPreviewRotation() == VideoRotation.None)
                    {
                        captureMgr.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
                    }
                    else if (captureMgr.GetPreviewRotation() == VideoRotation.Clockwise90Degrees)
                    {
                        captureMgr.SetPreviewRotation(VideoRotation.Clockwise180Degrees);
                    }
                    else if (captureMgr.GetPreviewRotation() == VideoRotation.Clockwise180Degrees)
                    {
                        captureMgr.SetPreviewRotation(VideoRotation.Clockwise270Degrees);
                    }
                    else if (captureMgr.GetPreviewRotation() == VideoRotation.Clockwise270Degrees)
                    {
                        captureMgr.SetPreviewRotation(VideoRotation.None);
                    }
                }
            }
    
            private void btnAddEffect_Click_1(object sender, RoutedEventArgs e)
            {
                AddEffectCapture(captureMgr);
            }
    
            private void btnRemoveEffect_Click_1(object sender, RoutedEventArgs e)
            {
                ClearEffectsCapture(captureMgr);
            }
    
            async void CaptureVideo()
            {
                // <SnippetCaptureVideoAll>
                // <SnippetCaptureVideoInit> 
                MediaCapture captureMgr = new MediaCapture();
                await captureMgr.InitializeAsync();
                // </SnippetCaptureVideoInit> 
    
                // <SnippetCaptureVideoStart>
                // 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();
                // </SnippetCaptureVideoStart>
                // </SnippetCaptureVideoAll> 
            }
    
            private void btnCapturePreview_Click_1(object sender, RoutedEventArgs e)
            {
                CaptureVideo();
            }
    
            // <SnippetPlaybackLocalFileAll>
            async private void SetLocalMedia()
            {
                // <SnippetPlaybackLocalFileFilePicker>
                var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
    
                openPicker.FileTypeFilter.Add(".wmv");
                openPicker.FileTypeFilter.Add(".mp4");
                openPicker.FileTypeFilter.Add(".wma");
                openPicker.FileTypeFilter.Add(".mp3");
    
                var file = await openPicker.PickSingleFileAsync();
                // </SnippetPlaybackLocalFileFilePicker>
    
                // <SnippetPlaybackLocalFileSetSource>
                // mediaControl is a MediaElement defined in XAML
                if (null != file)
                {
                    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
                    mediaControl.SetSource(stream, file.ContentType);
                    mediaControl.Play();
                }
                // </SnippetPlaybackLocalFileSetSource>
            }
            // </SnippetPlaybackLocalFileAll>
    
    
            private void btnPlayBackFilePicker_Click_1(object sender, RoutedEventArgs e)
            {
                SetLocalMedia();
            }
    
            // <SnippetMediaOpenedLiveStream>
            private void media_MediaOpened(object sender, RoutedEventArgs e)
            {
                bool isLive = IsLiveStream(sender as MediaElement);
            }
    
            private bool IsLiveStream(MediaElement media)
            {
                bool isLive = false;
    
                if (media.NaturalDuration.TimeSpan.Ticks == Int64.MaxValue)
                {
                   isLive = true;
                }
    
                return isLive;
            }
            // </SnippetMediaOpenedLiveStream>
    
    
    
            //private void btnFoo_Click_1(object sender, RoutedEventArgs e)
            //{
            //    foreach (UIElement x in StackFoo.Children)
            //    {
            //        if (x is Button)
            //        {
            //            txtDisplay.Text += ((Button)x).Name + "  ";
            //        }
            //    }
            //}
    
            // <SnippetTimelineMarker>
            private void Media_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
            {
                txOutput.Text =
                    string.Format("{0},{1},{2}", e.Marker.Time, e.Marker.Text, e.Marker.Type);
            }
            // </SnippetTimelineMarker>
        }
    }
    
  • MediaEnded
    MediaEnded
    MediaEnded
    MediaEnded

    Occurs when the MediaElement finishes playing audio or video.

    public event RoutedEventHandler MediaEndedpublic event RoutedEventHandler MediaEndedPublic Event MediaEnded
    <MediaElement MediaEnded="eventhandler" ../>
    
  • MediaFailed
    MediaFailed
    MediaFailed
    MediaFailed

    Occurs when there is an error associated with the media Source.

    public event ExceptionRoutedEventHandler MediaFailedpublic event ExceptionRoutedEventHandler MediaFailedPublic Event MediaFailed
    <MediaElement MediaFailed="eventhandler" .../>
    

    Remarks

    It is a best practice to always handle the MediaFailed event and take appropriate action.

    Examples

    The following code creates a MediaFailed event handler that calls a helper function to retrieve the HRESULT from the event arguments.

    private void videoMediaElement_MediaFailed(object sender, ExceptionRoutedEventArgs e)
    {
        // get HRESULT from event args 
        string hr = GetHresultFromErrorMessage(e);
    
        // Handle media failed event appropriately 
    }
    
    private string GetHresultFromErrorMessage(ExceptionRoutedEventArgs e)
    {
        String hr = String.Empty;
        String token = "HRESULT - ";
        const int hrLength = 10;     // eg "0xFFFFFFFF"
    
        int tokenPos = e.ErrorMessage.IndexOf(token, StringComparison.Ordinal);
        if (tokenPos != -1)
        {
            hr = e.ErrorMessage.Substring(tokenPos + token.Length, hrLength);
        }
    
        return hr;
    }
    
  • MediaOpened
    MediaOpened
    MediaOpened
    MediaOpened

    Occurs when the media stream has been validated and opened, and the file headers have been read.

    public event RoutedEventHandler MediaOpenedpublic event RoutedEventHandler MediaOpenedPublic Event MediaOpened
    <MediaElement MediaOpened="eventhandler" .../>
    

    Remarks

    Live media streams report a NaturalDuration of Int64.MaxValue.

    Any calls to Play(), Pause(), and Stop() methods that occur before the MediaOpened event is raised are ignored.

    Examples

    The following code shows how to determine if a media stream is a live stream.

    private void media_MediaOpened(object sender, RoutedEventArgs e)
    {
        bool isLive = IsLiveStream(sender as MediaElement);
    }
    
    private bool IsLiveStream(MediaElement media)
    {
        bool isLive = false;
    
        if (media.NaturalDuration.TimeSpan.Ticks == Int64.MaxValue)
        {
           isLive = true;
        }
    
        return isLive;
    }
    
  • PartialMediaFailureDetected
    PartialMediaFailureDetected
    PartialMediaFailureDetected
    PartialMediaFailureDetected

    Occurs when one or more streams fails to decode in content containing multiple streams.

    public event TypedEventHandler PartialMediaFailureDetectedpublic event TypedEventHandler PartialMediaFailureDetectedPublic Event PartialMediaFailureDetected

    Remarks

    If at least one stream in the content is successfully decoded, the decoded media is played and this event is raised. If the stream that fails to decode is the only stream contained in the content, playback fails and the MediaFailed event is raised.

  • RateChanged
    RateChanged
    RateChanged
    RateChanged

    Occurs when PlaybackRate or DefaultPlaybackRate value changes.

    public event RateChangedRoutedEventHandler RateChangedpublic event RateChangedRoutedEventHandler RateChangedPublic Event RateChanged
    <MediaElement RateChanged="eventhandler"/>
    
  • SeekCompleted
    SeekCompleted
    SeekCompleted
    SeekCompleted

    Occurs when the seek point of a requested seek operation is ready for playback.

    public event RoutedEventHandler SeekCompletedpublic event RoutedEventHandler SeekCompletedPublic Event SeekCompleted
    <MediaElement SeekCompleted="eventhandler"/>
    
  • VolumeChanged
    VolumeChanged
    VolumeChanged
    VolumeChanged

    Occurs when the value of the Volume property changes.

    public event RoutedEventHandler VolumeChangedpublic event RoutedEventHandler VolumeChangedPublic Event VolumeChanged
    <MediaElement VolumeChanged="eventhandler" />
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ActivatableAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.ThreadingAttribute

Details

Assembly

Windows.UI.Xaml.Controls.dll