MediaElement MediaElement MediaElement MediaElement Class

Definition

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

public : sealed class MediaElement : FrameworkElement, IMediaElement, IMediaElement2, IMediaElement3public sealed class MediaElement : FrameworkElement, IMediaElement, IMediaElement2, IMediaElement3Public NotInheritable Class MediaElement Inherits FrameworkElement Implements IMediaElement, IMediaElement2, IMediaElement3// This API is not available in Javascript.
<MediaElement .../>
Inheritance
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Inherited Members

Inherited properties

Inherited events

Inherited methods

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

Remarks

Important

In Windows 10, build 1607 and on we recommend that you use MediaPlayerElement in place of MediaElement. MediaPlayerElement has the same functionality as MediaElement, while also enabling more advanced media playback scenarios. Additionally, all future improvements in media playback will happen in MediaPlayerElement.

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.

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 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 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 to set the chosen media file as the MediaElement.Source.

To set the Source of the MediaElement to the StorageFile returned from the FileOpenPicker, you need to open a stream. Call the OpenAsync method on the StorageFile returns a stream that you can pass into the MediaElement.SetSource 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 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 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 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 DependencyProperty.RegisterPropertyChangedCallback to be notified when the MediaElement.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 DisplayRequest.RequestActive. To conserve power and battery life, you should call DisplayRequest.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 Window.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.

Constructors

MediaElement() MediaElement() MediaElement() MediaElement()

Instantiates a new instance of the MediaElement class.

public : MediaElement()public MediaElement()Public Sub New()// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
Stereo3DVideoPackingMode Stereo3DVideoPackingMode Stereo3DVideoPackingMode Stereo3DVideoPackingMode

A value of the enumeration. May be None if media engine is not ready for use.

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.

See Also

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// This API is not available in Javascript.

AreTransportControlsEnabled AreTransportControlsEnabled AreTransportControlsEnabled AreTransportControlsEnabled

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

public : PlatForm::Boolean AreTransportControlsEnabled { get; set; }public bool AreTransportControlsEnabled { get; set; }Public ReadWrite Property AreTransportControlsEnabled As bool// This API is not available in Javascript.
<MediaElement AreTransportControlsEnabled="bool" />
Value
PlatForm::Boolean bool bool bool

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

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" />

Remarks

The transport controls are exposed as a MediaTransportControls object that you can access through the MediaElement.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.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
int 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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
int 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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement AudioCategory="audioCategoryMemberName" /.
Value
AudioCategory AudioCategory AudioCategory AudioCategory

A value of the enumeration.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement AudioDeviceType="audioDeviceTypeMemberName" /.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
int 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// This API is not available in Javascript.

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 Nullable<int> AudioStreamIndex { get; set; }Public ReadWrite Property AudioStreamIndex As Nullable<int>// This API is not available in Javascript.
<MediaElement AudioStreamIndex="int"/>
Value
IReference<int> Nullable<int> Nullable<int> Nullable<int>

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// This API is not available in Javascript.

AutoPlay AutoPlay AutoPlay AutoPlay

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

public : PlatForm::Boolean AutoPlay { get; set; }public bool AutoPlay { get; set; }Public ReadWrite Property AutoPlay As bool// This API is not available in Javascript.
<MediaElement AutoPlay="bool" .../>
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the AutoPlay dependency property.

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// This API is not available in Javascript.
<MediaElement Balance="double"  .../>
Value
double 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Balance dependency property.

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// This API is not available in Javascript.
Value
double 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// This API is not available in Javascript.

CanPause CanPause CanPause CanPause

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

public : PlatForm::Boolean CanPause { get; }public bool CanPause { get; }Public ReadOnly Property CanPause As bool// This API is not available in Javascript.
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CanPause dependency property.

CanSeek CanSeek CanSeek CanSeek

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

public : PlatForm::Boolean CanSeek { get; }public bool CanSeek { get; }Public ReadOnly Property CanSeek As bool// This API is not available in Javascript.
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CanSeek dependency property.

CurrentState CurrentState CurrentState CurrentState

Gets the status of this MediaElement.

public : MediaElementState CurrentState { get; }public MediaElementState CurrentState { get; }Public ReadOnly Property CurrentState As MediaElementState// This API is not available in Javascript.
Value
MediaElementState MediaElementState MediaElementState MediaElementState

The current state of this MediaElement. The state can be one of the following (as defined in the MediaElementState enumeration): Buffering, Closed, Opening, Paused, Playing, or Stopped. The default value is Closed.

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CurrentState dependency property.

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// This API is not available in Javascript.
<MediaElement DefaultPlaybackRate="double"/>
Value
double 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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
double 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// This API is not available in Javascript.
Value
double 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// This API is not available in Javascript.

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// This API is not available in Javascript.

IsAudioOnly IsAudioOnly IsAudioOnly IsAudioOnly

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

public : PlatForm::Boolean IsAudioOnly { get; }public bool IsAudioOnly { get; }Public ReadOnly Property IsAudioOnly As bool// This API is not available in Javascript.
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the IsAudioOnly dependency property.

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 : PlatForm::Boolean IsFullWindow { get; set; }public bool IsFullWindow { get; set; }Public ReadWrite Property IsFullWindow As bool// This API is not available in Javascript.
<MediaElement IsFullWindow="bool" />
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the IsFullWindow dependency property.

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 : PlatForm::Boolean IsLooping { get; set; }public bool IsLooping { get; set; }Public ReadWrite Property IsLooping As bool// This API is not available in Javascript.
<MediaElement IsLooping="bool"/>
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the IsLooping dependency property.

IsMuted IsMuted IsMuted IsMuted

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

public : PlatForm::Boolean IsMuted { get; set; }public bool IsMuted { get; set; }Public ReadWrite Property IsMuted As bool// This API is not available in Javascript.
<MediaElement IsMuted="bool" .../>
Value
PlatForm::Boolean 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the IsMuted dependency property.

IsStereo3DVideo IsStereo3DVideo IsStereo3DVideo IsStereo3DVideo

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

public : PlatForm::Boolean IsStereo3DVideo { get; }public bool IsStereo3DVideo { get; }Public ReadOnly Property IsStereo3DVideo As bool// This API is not available in Javascript.
Value
PlatForm::Boolean 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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
TimelineMarkerCollection TimelineMarkerCollection TimelineMarkerCollection TimelineMarkerCollection

The collection of timeline markers (represented as TimelineMarker objects) associated with the currently loaded media file. The default is an empty collection.

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

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.

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// This API is not available in Javascript.
Value
Duration Duration Duration Duration

The natural duration of the media. The default value is a Duration structure that evaluates as Automatic, which is the value held if you query this property before MediaOpened.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
int 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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
int 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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement PlaybackRate="double"/>
Value
double 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the PlaybackRate dependency property.

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// This API is not available in Javascript.
<MediaElement PlayToPreferredSourceUri="uri" />
Value
Uri Uri Uri Uri

The path to the preferred media source.

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");

Remarks

PlayToSource.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 PlayToSource.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.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
PlayToSource PlayToSource PlayToSource PlayToSource

A reference object that carries the "PlayTo" source information.

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the PlayToSource dependency property.

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// This API is not available in Javascript.
Value
TimeSpan TimeSpan TimeSpan TimeSpan

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 Windows::Foundation::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 MediaElement.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".

See Also

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement PosterSource="imageUri" />
Value
ImageSource ImageSource ImageSource ImageSource

An image source for a transition ImageBrush that is applied to the MediaElement content area.

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the PosterSource dependency property.

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// This API is not available in Javascript.
Value
MediaProtectionManager MediaProtectionManager MediaProtectionManager MediaProtectionManager

The dedicated object for media content protection.

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// This API is not available in Javascript.

RealTimePlayback RealTimePlayback RealTimePlayback RealTimePlayback

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

public : PlatForm::Boolean RealTimePlayback { get; set; }public bool RealTimePlayback { get; set; }Public ReadWrite Property RealTimePlayback As bool// This API is not available in Javascript.
<MediaElement RealTimePlayback="bool" />
Value
PlatForm::Boolean 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.

See Also

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement Source="uri" .../>
Value
Uri Uri Uri Uri

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Source dependency property.

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// This API is not available in Javascript.
<MediaElement Stereo3DVideoPackingMode="stereo3DVideoPackingModeMemberName" .../>

Examples

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

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. Stereo3DVideoPackingMode is used in conjunction with Stereo3DVideoRenderMode to display 3-D content.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement Stereo3DVideoRenderMode="stereo3DVideoRenderModeMemberName" .../>

Examples

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

Remarks

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

Set Stereo3DVideoRenderMode to Stereo 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

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement Stretch="stretchMemberName" />
Value
Stretch Stretch Stretch Stretch

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

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

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.
See Also

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Stretch dependency property.

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<MediaElement Volume="double"/>
Value
double 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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Volume dependency property.

Methods

AddAudioEffect(String, Boolean, IPropertySet) AddAudioEffect(String, Boolean, IPropertySet) AddAudioEffect(String, Boolean, IPropertySet) AddAudioEffect(String, Boolean, IPropertySet)

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

public : void AddAudioEffect(PlatForm::String effectID, bool effectOptional, IPropertySet effectConfiguration)public void AddAudioEffect(String effectID, Boolean effectOptional, IPropertySet effectConfiguration)Public Function AddAudioEffect(effectID As String, effectOptional As Boolean, effectConfiguration As IPropertySet) As void// This API is not available in Javascript.
Parameters
effectID
PlatForm::String String String String

The identifier for the desired effect.

effectOptional
bool Boolean Boolean 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
IPropertySet IPropertySet IPropertySet IPropertySet

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(String, Boolean, IPropertySet) AddVideoEffect(String, Boolean, IPropertySet) AddVideoEffect(String, Boolean, IPropertySet) AddVideoEffect(String, Boolean, IPropertySet)

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

public : void AddVideoEffect(PlatForm::String effectID, bool effectOptional, IPropertySet effectConfiguration)public void AddVideoEffect(String effectID, Boolean effectOptional, IPropertySet effectConfiguration)Public Function AddVideoEffect(effectID As String, effectOptional As Boolean, effectConfiguration As IPropertySet) As void// This API is not available in Javascript.
Parameters
effectID
PlatForm::String String String String

The identifier for the desired effect.

effectOptional
bool Boolean Boolean 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
IPropertySet IPropertySet IPropertySet IPropertySet

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

CanPlayType(String) CanPlayType(String) CanPlayType(String) CanPlayType(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(PlatForm::String type)public MediaCanPlayResponse CanPlayType(String type)Public Function CanPlayType(type As String) As MediaCanPlayResponse// This API is not available in Javascript.
Parameters
type
PlatForm::String String String String

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

Returns

A value of the enumeration that describes the likelihood that the current media engine can play the source.

GetAsCastingSource() GetAsCastingSource() GetAsCastingSource() GetAsCastingSource()

Returns the media element as a CastingSource.

public : CastingSource GetAsCastingSource()public CastingSource GetAsCastingSource()Public Function GetAsCastingSource() As CastingSource// This API is not available in Javascript.
Returns

Remarks

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

See Also

GetAudioStreamLanguage(IReference) GetAudioStreamLanguage(IReference) GetAudioStreamLanguage(IReference) GetAudioStreamLanguage(IReference)

Returns the RFC 1766 language for the specified audio stream.

public : PlatForm::String GetAudioStreamLanguage(IReference<int> index)public string GetAudioStreamLanguage(Nullable<Int32> index)Public Function GetAudioStreamLanguage(index As Nullable<Int32>) As string// This API is not available in Javascript.
Parameters
index
IReference<int> Nullable<Int32> Nullable<Int32> Nullable<Int32>

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
PlatForm::String 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// This API is not available in Javascript.

Play() Play() Play() Play()

Plays media from the current position.

public : void Play()public void Play()Public Function Play() As void// This API is not available in Javascript.

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// This API is not available in Javascript.

SetMediaStreamSource(IMediaSource) SetMediaStreamSource(IMediaSource) SetMediaStreamSource(IMediaSource) SetMediaStreamSource(IMediaSource)

Sets the Source of the MediaElement to the specified MediaStreamSource.

public : void SetMediaStreamSource(IMediaSource source)public void SetMediaStreamSource(IMediaSource source)Public Function SetMediaStreamSource(source As IMediaSource) As void// This API is not available in Javascript.
Parameters

SetPlaybackSource(IMediaPlaybackSource) SetPlaybackSource(IMediaPlaybackSource) SetPlaybackSource(IMediaPlaybackSource) SetPlaybackSource(IMediaPlaybackSource)

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

public : void SetPlaybackSource(IMediaPlaybackSource source)public void SetPlaybackSource(IMediaPlaybackSource source)Public Function SetPlaybackSource(source As IMediaPlaybackSource) As void// This API is not available in Javascript.
Parameters

SetSource(IRandomAccessStream, String) SetSource(IRandomAccessStream, String) SetSource(IRandomAccessStream, String) SetSource(IRandomAccessStream, String)

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

public : void SetSource(IRandomAccessStream stream, PlatForm::String mimeType)public void SetSource(IRandomAccessStream stream, String mimeType)Public Function SetSource(stream As IRandomAccessStream, mimeType As String) As void// This API is not available in Javascript.
Parameters
stream
IRandomAccessStream IRandomAccessStream IRandomAccessStream IRandomAccessStream

The stream that contains the media to load.

mimeType
PlatForm::String String String 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.

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

Remarks

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

See Also

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// This API is not available in Javascript.

Events

BufferingProgressChanged BufferingProgressChanged BufferingProgressChanged BufferingProgressChanged

Occurs when the BufferingProgress property changes.

public : event RoutedEventHandler BufferingProgressChangedpublic event RoutedEventHandler BufferingProgressChangedPublic Event BufferingProgressChanged// This API is not available in Javascript.
<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// This API is not available in Javascript.
<MediaElement CurrentStateChanged="eventhandler"/>

DownloadProgressChanged DownloadProgressChanged DownloadProgressChanged DownloadProgressChanged

Occurs when the DownloadProgress property has changed.

public : event RoutedEventHandler DownloadProgressChangedpublic event RoutedEventHandler DownloadProgressChangedPublic Event DownloadProgressChanged// This API is not available in Javascript.
<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// This API is not available in Javascript.
<MediaElement MarkerReached="eventhandler"/>

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

MediaEnded MediaEnded MediaEnded MediaEnded

Occurs when the MediaElement finishes playing audio or video.

public : event RoutedEventHandler MediaEndedpublic event RoutedEventHandler MediaEndedPublic Event MediaEnded// This API is not available in Javascript.
<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// This API is not available in Javascript.
<MediaElement MediaFailed="eventhandler" .../>

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

Remarks

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

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// This API is not available in Javascript.
<MediaElement MediaOpened="eventhandler" .../>

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

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.

PartialMediaFailureDetected PartialMediaFailureDetected PartialMediaFailureDetected PartialMediaFailureDetected

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

public : event TypedEventHandler PartialMediaFailureDetected<MediaElement,  PartialMediaFailureDetectedEventArgs>public event TypedEventHandler PartialMediaFailureDetected<MediaElement,  PartialMediaFailureDetectedEventArgs>Public Event PartialMediaFailureDetected<MediaElement,  PartialMediaFailureDetectedEventArgs>// This API is not available in Javascript.

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// This API is not available in Javascript.
<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// This API is not available in Javascript.
<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// This API is not available in Javascript.
<MediaElement VolumeChanged="eventhandler" />

See Also