Skip to content

Latest commit

 

History

History
283 lines (209 loc) · 17.4 KB

mediaplayerelement.md

File metadata and controls

283 lines (209 loc) · 17.4 KB
-api-id -api-type
T:Windows.UI.Xaml.Controls.MediaPlayerElement
winrt class

Windows.UI.Xaml.Controls.MediaPlayerElement

-description

Represents an object that uses a MediaPlayer to render audio and video to the display.

-xaml-syntax

<MediaPlayerElement .../>

-remarks

Tip

For more info, design guidance, and code examples, see Media playback.

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

Architectural overview

MediaPlayerElement is a lightweight XAML control that serves as a rendering surface for the robust MediaPlayer class, which is part of the Windows.Media.Playback namespace. The majority of the media functionality is located on the underlying MediaPlayer class, which you can access through the MediaPlayerElement.MediaPlayer property.

For more information about the MediaPlayer class, including guidelines on how to transition from MediaElement to MediaPlayerElement, see the Media playback page.

Set the media source

Set the Source property of the MediaPlayerElement to point to an audio or video file. You can set it to a MediaSource, MediaPlaybackItem, or MediaPlaybackList. The media files can be included with the app package or be on a network.

By default, the media that is defined by the Source property does not immediately play after the MediaPlayerElement object has loaded. To start media playback automatically, set the AutoPlay property to true.

Here's how to create a MediaPlayerElement 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 true.

<MediaPlayerElement Source="ms-appx:///Media/video1.mp4" AutoPlay="True"/>

Here’s how to create the MediaPlayerElement in code.

MediaPlayerElement mediaPlayerElement1 = new MediaPlayerElement();
mediaPlayerElement1.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Media/video1.mp4"));
mediaPlayerElement1.AutoPlay = true;

Set the underlying media player

When the Source property or AutoPlay property is set on MediaPlayerElement, it will automatically create an underlying MediaPlayer if one doesn't already exist. Alternatively, you can create your own MediaPlayer and set it on MediaPlayerElement using the SetMediaPlayer method. Here's an example of how to set the underlying MediaPlayer in code.

<MediaPlayerElement x:Name="mpe"/>
MediaPlayer mediaPlayer = new MediaPlayer();
mpe.SetMediaPlayer(mediaPlayer);
mpe.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Media/video1.mp4"));
mpe.AutoPlay = true;

Note

Setting MediaPlayerElement properties will set the corresponding properties on its underlying MediaPlayer. You have the option to use the underlying MediaPlayer directly instead of using MediaPlayerElement properties. Be aware that using MediaPlayer directly where an equivalent MediaPlayerElement property could otherwise be used can cause unexpected behavior. This is because the MediaPlayerElement is not aware of everything happening to its underlying MediaPlayer. For example, if you set the source directly on MediaPlayer, then MediaPlayerElement's Source property will not reflect the change. For this reason, you must be consistent in using MediaPlayerElement properties or directly using the underlying MediaPlayer. This documentation will use MediaPlayerElement properties whenever possible.

Detach the underlying media player

The MediaPlayer is detached from MediaPlayerElement when the MediaPlayerElement is destroyed or when a new MediaPlayer is set using SetMediaPlayer. When detached, MediaPlayerElement treats the underlying MediaPlayer differently depending on whether it was created by MediaPlayerElement or set using SetMediaPlayer.

If the MediaPlayer was created by MediaPlayerElement, it will properly Close the MediaPlayer for you.

If the MediaPlayer was set on MediaPlayerElement using SetMediaPlayer, you are responsible for ensuring the MediaPlayer is properly closed. Failing to do so may result in fatal playback errors in MediaPlayer. Here's how to properly detach and Close MediaPlayer in code.

<MediaPlayerElement x:Name="mpe"/>
MediaPlayer mediaPlayer = mpe.MediaPlayer;
IMediaPlaybackSource source = mpe.Source;

// 1. Pause playback if able.
if (mediaPlayer.PlaybackSession.CanPause)
{
    mediaPlayer.Pause();
}

// 2. Disconnect the MediaPlayer from its source. This can be done by setting 
//    the MediaPlayerElement Source property to null or by directly setting the
//    source to null on the underlying MediaPlayer.
mpe.Source = null;

// 3. Disconnect the MediaPlayer from MediaPlayerElement.
mpe.SetMediaPlayer(null);

// 4. Dispose of the MediaPlayer or Source if they're no longer needed.
if (source is MediaSource mediaSource)
{
    mediaSource.Dispose();
}
mediaPlayer.Dispose();

Handle media events

You can respond to common media events located on the underlying MediaPlayer such as MediaOpened, MediaEnded, and MediaFailed. If you have set the source to a MediaPlaybackItem or MediaPlaybackList, you should respond to the media events on those classes instead as they provide more information.

Transport controls

Set the AreTransportControlsEnabled property to programmatically enable and disable the built in transport controls for the MediaPlayerElement. 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, closed captions and remaining time.

You can create your own media transport controls by setting AreTransportControlsEnabled to false, and using the Play and Pause methods on MediaPlayer. You can also control a rich set of properties by using the underlying MediaPlayer such as Position, Volume, IsMuted, IsLoopingEnabled, and PlaybackRate.

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.

Full window playback

Use the IsFullWindow property to enable and disable full window rendering. When in full-window mode the display is automatically prevented from being deactivated when user action is no longer detected.

Note

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

Keep media playing

To prevent the display from being deactivated when MediaPlayerElement is not in full-window mode, 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 PlaybackStateChanged event to detect these situations. Then, use the NaturalVideoHeight property of the MediaPlayer.PlaybackSession to determine whether an audio or video file is playing, and keep the screen active only if video is playing.

<MediaPlayerElement x:Name="mpe" Source="ms-appx:///Media/video1.mp4"/>
// Create this variable at a global scope. Set it to null.
private DisplayRequest appDisplayRequest = null;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    mpe.MediaPlayer.PlaybackSession.PlaybackStateChanged += MediaPlayerElement_CurrentStateChanged;
    base.OnNavigatedTo(e);
}

private void MediaPlayerElement_CurrentStateChanged(MediaPlaybackSession sender, object args)
{
    MediaPlaybackSession playbackSession = sender as MediaPlaybackSession;
    if (playbackSession != null && playbackSession.NaturalVideoHeight != 0)
    {
        if(playbackSession.PlaybackState == MediaPlaybackState.Playing)
        {
            if(appDisplayRequest == null)
            {
                // This call creates an instance of the DisplayRequest object
                appDisplayRequest = new DisplayRequest();
                appDisplayRequest.RequestActive();
            }
        }
        else // PlaybackState is Buffering, None, Opening, or Paused.
        {
            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 MediaPlayerElement with a visual representation before the media is loaded or while audio-only media is playing. . A PosterSource is an image, such as a screen shot, movie poster, or album cover, 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.

-examples

Tip

For more info, design guidance, and code examples, see Media playback.

If you have the WinUI 2 Gallery app installed, click here to open the app and see the MediaPlayerElement in action.

This code creates a MediaPlayerElement 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.

<MediaPlayerElement Source="ms-appx:///Media/video1.mp4" AutoPlay="True" />

This example creates a MediaPlayerElement with the transport controls enabled.

<MediaPlayerElement x:Name="mediaPlayer"
              Source="ms-appx:///Media/video1.mp4"
              AreTransportControlsEnabled="True" />

This example shows how to use a MediaPlayerElement in a Popup.

<Grid>
    <Button Content="Show Popup" Click="ShowPopupClicked"/>
    <Popup x:Name="mediaPlayerPopup">
        <StackPanel Height="1400" Width="1400" Background="Blue">
            <MediaPlayerElement x:Name="mediaPlayer"
                  AreTransportControlsEnabled="True"
                  Source="ms-appx:///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(MediaPlayerElement.IsFullWindowProperty, OnMPEFullWindowChanged);
    base.OnNavigatedTo(e);
}

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

private void OnMPEFullWindowChanged(DependencyObject sender, DependencyProperty dp)
{
    MediaPlayerElement mpe = (MediaPlayerElement)sender;

    if (mpe != null && dp == MediaPlayerElement.IsFullWindowProperty)
    {
        if (mpe.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; }
}

-see-also

Control, Media playback overview, Audio categories sample, Media transport controls sample, Version adaptive code sample