Поделиться через


Quickstart: video and audio (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

Play audio and video media using a MediaElement in your Windows Runtime app using C++, C#, or Visual Basic.

Roadmap: How does this topic relate to others? See:

Introduction

To play audio and video media in your Windows Runtime app using C++, C#, or Visual Basic, use the MediaElement class. MediaElement provides numerous properties and methods for controlling audio and video playback. We will go over the basics for creating and using a MediaElement.

Windows 8.1 introduces built in transport controls for the MediaElement. They handle play, stop, pause, volume, mute, seeking/progress, and audio track selection. To enable theses controls, set AreTransportControlsEnabled to true. To disable them, set AreTransportControlsEnabled to false.

Windows 8.1 introduces a IsFullWindow property to enable and disable full window rendering. This insures that system optimizations are enabled when switching to full window rendering. In Windows 8.1 and later, you should always use the IsFullWindow property to enable and disable full window rendering.

Prior to Windows 8.1, the developer is responsible for creating custom UI for controlling audio and video playback. For example, to start the media in your app you could create a Button and call Play in the Button event handler. Though Windows 8.1 introduces built in transport controls, there are still times when you may need to create custom UI to support additional functionality or you may want to replace the built-in controls with your own. For a more in-depth discussion on creating custom transport controls, see How to create custom media transport controls.

MediaElement basics

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.

Here is some code that creates a MediaElement and sets its Source property to the URI of a video file. 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" 
              Source="Videos/video1.mp4" 
              Width="400" AutoPlay="False"/>

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

Working with MediaElement properties

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

Property Description
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

Introduced in Windows 8.1.

Enables or disables full window rendering. You should always use the IsFullWindow property to enable and disable full window rendering. This insures that system optimizations are enabled.

AreTransportControlsEnabled

Introduced in Windows 8.1.

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

Introduced in Windows 8.1.

The MediaElement.Stretch property defines how the MediaElement fills the space of the container it is in. 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 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.

 

Controlling media playback

Windows 8.1 introduces built in transport controls for controlling the media playback. To enable the built in transport controls set AreTransportControlsEnabled to true. This is the easiest way control the MediaElement playback. But if you want to add your own UI to control playback, this sections shows how to manually hook into the playback methods on the MediaElement. This can be used to add support for features not in the built in controls or for replacing the built in controls with your own custom controls.

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

Method Description
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. See the MediaElement reference page for a full listing.

Method Description
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.

 

Here is some code that creates a MediaElement and a number of Button objects to control the media playback. The MediaElement listens to the MediaOpened, MediaEnded, and MediaFailed events. And it creates UI to handle Play, Stop, and Pause.

<StackPanel HorizontalAlignment="Center">
    <MediaElement x:Name="media" 
                  Source="Videos/Video1.mp4" 
                  Width="300"
                  AreTransportControlsEnabled="False"
                  MediaFailed="Media_MediaFailed"
                  MediaOpened="Media_MediaOpened"
                  MediaEnded="Media_MediaEnded" />
    
    <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Center">
        
        <Button Content="Play" Click="Play_Click"/>
        <Button Content="Pause" Click="Pause_Click"/>
        <Button Content="Stop" Click="Stop_Click" />
        
    </StackPanel>
</StackPanel>
void Play_Click(object sender, RoutedEventArgs e)
{
    media.Play();
}

void Pause_Click(object sender, RoutedEventArgs e)
{
    if (media.CanPause)
    {
        media.Pause();
    }
}

void Stop_Click(object sender, RoutedEventArgs e)
{
    media.Stop();
}

void Media_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
    // Handle failed media event
}

void Media_MediaOpened(object sender, RoutedEventArgs e)
{
    // Handle open media event
}

void Media_MediaEnded(object sender, RoutedEventArgs e)
{
    // Handle media ended event
}

Note  In addition to stopping, pausing, or playing media, you can also seek to a specific position by setting the Position property of a MediaElement object.

 

Setting 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 change the source media file, set Source to a Uri that contains the path to the file.

The SetSource method takes a 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. For more info on using the FileOpenPicker control, see How to open media files using the FileOpenPicker control.

To open files on the internet or files embedded in the app, set the Source property to the Uri of the media file. It is a good practice to put the code that sets the source in a try/catch block. For more info on opening media files over the network, see How to play media files from the network.

Preventing the screen from dimming

To prevent the display from be deactivating when user action is no longer detected, such as when an app is playing full-screen video, you can call DisplayRequest.RequestActive.

To conserve power and battery life, you should call DisplayRequest.RequestRelease to release the display request when it is no longer required, such as when the media is paused or stopped, when the media ends, or when the app is suspended.

See the Display power state sample and How to keep the display on during audio/video playback for more info.

PlayTo and media

You can use Play To to easily stream audio, video, or images from a computer to devices in their home network. For more information on enabling Play To in your Windows Store app using C++, C#, or Visual Basic, see Quickstart: Using PlayTo in applications.

Supported media formats

For info on supported audio and video media formats in Windows Store apps, see Supported audio and video formats.

Roadmaps

Roadmap for Windows Runtime apps using C# and Visual Basic

Roadmap for Windows Runtime apps using C++

Designing UX for apps

Adding multimedia

Samples

XAML media playback sample

Transcoding media sample

Media capture sample

Display power state sample

Media playback, start to finish

Tasks

How to create custom media transport controls

How to open media files using the FileOpenPicker control

How to select audio tracks in different languages

How to open media files from the network

How to use the system media transport controls

How to resize and stretch video

How to play audio in the background

Reference

MediaElement

Play

PlaybackRate

IValueConverter

AudioStreamIndex

Other resources

Supported audio and video formats

Optimize media resources