The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.


[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see the archive ]

Play audio and video media using a MediaElement in your Universal Windows Platform (UWP) app. Here, we show you how to create a MediaElement and use it to play audio and video files that are embedded in your app, from the local system, or from a network location.

MediaElement usage

Add media to your app by creating a MediaElement object in XAML and set the Source to a Uniform Resource Identifier (URI) that points to an audio or video file.

This XAML creates a MediaElement and sets its Source property to the URI of a video file that's local to the app. The MediaElement begins playing when the page loads. To suppress media from starting right away, you can set the AutoPlay property to false.

<MediaElement x:Name="mediaSimple" 
              Width="400" AutoPlay="False"/>

This XAML creates a MediaElement with the built in transport controls enabled and the AutoPlay property set to false.

<MediaElement x:Name="mediaPlayer" 

Transport controls

MediaElement has built in transport controls that handle play, stop, pause, volume, mute, seeking/progress, and audio track selection. To enable these controls, set AreTransportControlsEnabled to true. To disable them, set AreTransportControlsEnabled to false. The transport controls are represented by the MediaTransportControls class. You can use the transport controls as-is, or customize them in various ways. For more info, see the MediaTransportControls class reference and Create custom transport controls.

The transport controls let the user control most aspects of the MediaElement, but the MediaElement also provides numerous properties and methods that you can use to control audio and video playback. For more info, see the Control MediaElement programmatically section later in this article.

You can also integrate MediaElement with the system media transport controls. The system transport controls are the controls that pop up when hardware media keys are pressed, such as the media buttons on keyboards. If the user presses the pause key on a keyboard and your app supports the SystemMediaTransportControls, your app is notified and you can take the appropriate action. For more info, see System Media Transport Controls.

Set the media source

You can set the source of the MediaElement with either the Source property or the SetSource method.

The Source property type is Uri. To open files on the network or files embedded in the app, set Source to a Uri that contains the path to the file. It is a good practice to put the code that sets the source in a try/catch block.

The SetSource method takes an IRandomAccessStream, which is the media source, and the MIME type of the media. The FileOpenPicker is an easy way to get a stream object for a file on the local file system or Microsoft OneDrive.

Set the Source property to a URI

To play files on the network or files embedded with the app, set the Source property to the path of the file.

Tip  To open files from the internet, you need to declare the Internet (Client) capability in your app's manifest (Package.appxmanifest). For more info about declaring capabilities, see App capability declarations.

This code attempts to set the Source property of the MediaElement defined in XAML to the path of a file entered into a TextBox.

<TextBox x:Name="txtFilePath" Width="400" 
         Header="File path"
         PlaceholderText="Enter file path"/>

private void TxtFilePath_KeyUp(object sender, KeyRoutedEventArgs e)
    if (e.Key == Windows.System.VirtualKey.Enter)
        TextBox tbPath = sender as TextBox;

        if (tbPath != null)

private void LoadMediaFromString(string path)
        Uri pathUri = new Uri(path);
        mediaPlayer.Source = pathUri;
    catch (Exception ex)
        if (ex is FormatException)
            // handle exception. 
            // For example: Log error or notify user problem with file

To set the media source to a media file embedded in the app, create a Uri with the path prefixed with ms-appx:/// and then set the Source to it. For example, for a file called video1.mp4 that is in a Videos subfolder, the path would look like: ms-appx:///Videos/video1.mp4

This code sets the Source property of the MediaElement defined previously in XAML to ms-appx:///Videos/video1.mp4.

private void LoadEmbeddedAppFile()
        Uri pathUri = new Uri("ms-appx:///Videos/video1.mp4");
        mediaPlayer.Source = pathUri;
    catch (Exception ex)
        if (ex is FormatException)
            // handle exception. 
            // For example: Log error or notify user problem with file

Open local media

To open files on the local system or from 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.

Mt187272.wedge(en-us,WIN.10).gifTo 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 displays. Call PickSingleFileAsync to launch the file picker and get the file.

  2. 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, which 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();


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


Set the 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 occurs).
  • While media is loading. For example, a valid source is set, but the MediaOpened event has not occurred yet.
  • When media is streaming to another device.
  • When the media is audio only.

Here's a MediaElement with its Source set to an album track, and it's PosterSource set to an image of the album cover.

<MediaElement Source="Media/Track1.mp4" PosterSource="Media/AlbumCover.png"/> 

Keep the screen active

Typically, a device dims the display (and eventually turns it off) to save battery life when the user is away, but video apps need to keep the screen on so the user can see the video. To prevent the display from being deactivated when user action is no longer detected, such as when an app is playing full-screen video, you can call DisplayRequest.RequestActive. The DisplayRequest class lets you tell Windows to keep the display turned on so the user can see the video.

To conserve power and battery life, you should call DisplayRequest.RequestRelease to release the display request when it is no longer required. Windows automatically deactivates your app's active display requests when your app moves off screen, and re-activates them when your app comes back to the foreground.

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.

Mt187272.wedge(en-us,WIN.10).gifTo keep the screen active

  1. Create a global DisplayRequest variable. Initialize it to null.

    // Create this variable at a global scope. Set it to null.
    private DisplayRequest appDisplayRequest = null;
  2. Call RequestActive to notify Windows that the app requires the display to remain on.

  3. Call RequestRelease to release the display request whenever video playback is stopped, paused, or interrupted by a playback error. When your app no longer has any active display requests, Windows saves battery life by dimming the display (and eventually turning it off) when the device is not being used.

    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"
    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();
            else // CurrentState is Buffering, Closed, Opening, Paused, or Stopped. 
                if (appDisplayRequest != null)
                    // Deactivate the display request and set the var to null.
                    appDisplayRequest = null;

Control MediaElement programmatically

MediaElement provides numerous properties, methods, and events for controlling audio and video playback.

Common properties, methods, and events

The MediaElement object provides several media-specific properties. Here are some of the common properties. For a full listing of properties, methods, and events, see the MediaElement reference page .

AutoPlay Specifies whether the MediaElement should begin playing automatically. The default value is true.
IsMuted Specifies whether the volume is muted. The default value is false.
IsFullWindow Enables or disables full window rendering. You should always use the IsFullWindow property to enable and disable full window rendering. This ensures that system optimizations are enabled.
AreTransportControlsEnabled Enables or disables the built in transport controls.
Volume Specifies the audio volume from a range of 0 to 1 with 1 being the loudest.
Balance Specifies the ratio of volume across stereo speakers from a range of -1 to 1. The default value is 0.
CurrentState Specifies the current state of the MediaElement.
IsAudioOnly Specifies if the current media source is audio-only.
IsLooping Specifies if the current media is set to restart at the beginning when the end of the media is reached.
NaturalDuration Specifies the duration of the media file currently opened.
Position Specifies the current playback position. You can seek to another point in the media time-line by setting the Position to a specific point in on the time-line.
PosterSource Specifies the image source that is used for a placeholder image while the media is loading.
Source Specifies the source URI of the audio or video file.
AudioStreamCount Specifies the number of audio streams that exist in the current media file.
AudioStreamIndex Specifies the audio stream that plays along with the video component.
Stretch The MediaElement.Stretch property defines how the MediaElement fills the space of the container it is in.


The MediaElement object provides several media-specific methods for controlling media playback. Here are some of the common methods. For a full listing, see the MediaElement reference page.

Play Plays media from the current position.
Pause Pauses media at the current position.
Stop Stops the media and resets the media Position to 0.
SetSource Sets the Source property using the supplied stream.


The MediaElement object provides several media-specific events. Here are some of the common events. For a full listing, see the MediaElement reference page.

MediaOpened Occurs when the media stream has been validated and opened, and the file headers have been read.
MediaEnded Occurs when the MediaElement finishes playing audio or video.
MediaFailed Occurs when there is an error associated with the media Source.
CurrentStateChange Occurs when the value of the CurrentState property changes.


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.

Mt187272.wedge(en-us,WIN.10).gifTo 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.

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

  3. 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;

Enable full window video rendering

Set the IsFullWindow property to enable and disable full window rendering. When you programmatically set full window rendering in your app, you should always use IsFullWindow instead of doing it manually. IsFullWindow insures that system level optimizations are performed that improve performance and battery life. If full window rendering is not set up correctly, these optimizations may not be enabled.

Here is some code that creates an AppBarButton that toggles full window rendering.

<AppBarButton Icon="FullScreen" 
              Label="Full Window"

private void FullWindow_Click(object sender, object e)
    mediaPlayer.IsFullWindow = !media.IsFullWindow;

Resize and stretch video

Use the Stretch property to change how the video content fills the container it's in. This resizes and stretches the video depending on the Stretch value. The Stretch states are similar to picture size settings on many TV sets. You can hook this up to a button and allow the user to choose which setting they prefer.

  • None displays the native resolution of the content in its original size.
  • Uniform fills up as much of the space as possible while preserving the aspect ratio and the image content. This can result in horizontal or vertical black bars at the edges of the video. This is similar to wide-screen modes.
  • UniformToFill fills up the entire space while preserving the aspect ratio. This can result in some of the image being cropped. This is similar to full-screen modes.
  • Fill fills up the entire space, but does not preserve the aspect ratio. None of image is cropped, but stretching may occur. This is similar to stretch modes.
Stretch enumeration values

Here, an AppBarButton is used to cycle through the Stretch options. A switch statement checks the current state of the Stretch property and sets it to the next value in the Stretch enumeration. This lets the user cycle through the different stretch states.

<AppBarButton Icon="Switch" 
              Label="Resize Video"
              Click="PictureSize_Click" />

private void PictureSize_Click(object sender, RoutedEventArgs e)
    switch (mediaPlayer.Stretch)
        case Stretch.Fill:
            mediaPlayer.Stretch = Stretch.None;
        case Stretch.None:
            mediaPlayer.Stretch = Stretch.Uniform;
        case Stretch.Uniform:
            mediaPlayer.Stretch = Stretch.UniformToFill;
        case Stretch.UniformToFill:
            mediaPlayer.Stretch = Stretch.Fill;

Enable low-latency playback

Set the RealTimePlayback property to true on a MediaElement to enable the media element to reduce the initial latency for playback. This is critical for two-way communications apps, and can be applicable to some gaming scenarios. Be aware that this mode is more resource intensive and less power-efficient.

This example creates a MediaElement and sets RealTimePlayback to true.

<MediaElement x:Name="mediaPlayer" RealTimePlayback="True"/>

MediaElement mediaPlayer = new MediaElement();
mediaPlayer.RealTimePlayback = true;


This article is for Windows 10 developers writing Universal Windows Platform (UWP) apps. If you’re developing for Windows 8.x or Windows Phone 8.x, see the archived documentation.


Related topics