Compartilhar via


Media playback, start to finish (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 ]

Learn how to create feature-rich media apps for Windows 8.1 that play audio and video and that conserve battery life and optimize rendering.

We'll go over how to create a Windows Store app using C++, C#, or Visual Basic loaded with media features, from start to finish. There are lots of improvements in Windows 8.1 that make this even easier than before, such as the new transport controls for the MediaElement class. We'll cover those, plus:

  • Media playback basics like creating a MediaElement, enabling the transport controls, and loading media files from either the device or the network.
  • Media playback features like properly preventing the screen from dimming, playing audio in the background, interacting with the system media transport controls, resizing video, creating custom transport controls, and enabling full-window rendering.
  • App basics like preserving app state, creating UI on the app bar, creating Settings flyouts, and animating UI.

If you're new to developing Windows Store apps using C++, C#, or Visual Basic, take a look at Create your first Windows Store app using C# or Visual Basic to get up to speed.

Each step below links to a how-to topic with examples and code, so dig into those if you want more info.

The Media playback, start to finish sample includes all the things we talk about here. We'll refer to this companion sample often and point you to the places in it where specific features are implemented.

Create a media app

Create your sample

If you want to follow the steps here to add media features to your own app, you can create a blank Windows Store app project in Microsoft Visual Studio and add a Basic item. The Basic item automatically includes useful helper classes like SuspensionManager.cs that simplify saving app state and handling app suspend and unsuspend. To add a Basic item, in Visual Studio select Project>Add New Item>Basic Item.

Or, skip directly to the Media playback, start to finish companion sample.

The companion sample implements all the steps here, but to keep things moving we won't walk through the code. Each step has a "Find it in the sample" section to help you find the code quickly.

The structure of the sample's source files is simple and flat so you can easily find code without having to drill down through multiple layers of source files. But you may prefer to break up and organize your own project differently.

 

Media playback basics

Playing audio and video basics

Set up the basics for playing audio and video in your app. The how-to topic goes into detail about how to do that, but to get basic audio and video playing, just add a MediaElement object to your XAML and set the Source to a media file.

The MediaElement class plays both video and audio.

To control the media playback, Windows 8.1 introduces new, built-in transport controls. Enable and disable the controls by setting the AreTransportControlsEnabled property. Transport controls provide common media UI elements like the play button and volume controls. Here's how those controls look in the sample.

Find it in the sample: The MediaElement is named media and is defined in XAML in the file MainPage.xaml.

Supported audio and video formats

Windows Store apps using C++, C#, or Visual Basic support a large number of audio and video formats. Click the link for the complete list.

How to open media files using the FileOpenPicker control

Now that we have media playing, let's set the media source while the app is running.

The FileOpenPicker control lets the user select a file from the local file system or from Microsoft OneDrive. This step shows how to set up the FileOpenPicker and how to set the MediaElement.Source property to the file returned by the FileOpenPicker.

Use StorageApplicationPermissions.FutureAccessList to store permissions for files opened with the FileOpenPicker. Your app can then access the files later on, such as when the app is being restored from a termination state.

The FileOpenPicker looks like this.

The FileOpenPicker doesn't require your app to declare capabilities for system folders such as Music, Videos, and Documents. This is because the user has total control over the FileOpenPicker and over which files are opened. For security and privacy purposes, your app should declare as few capabilities as possible. But if you want your app to have access to the Videos and Music folders without the user's input—to display all the album art in the Music folder, for example—you must declare the corresponding capabilities. For more info, see App capability declarations.

Find it in the sample: Look at the Browse_Click and SetMediaSourceFromFile methods in MainPage.xaml.cs and the appBarTextBoxFilePathTextBlock in MainPage.xaml.

How to play media files from the network

The FileOpenPicker control works well for getting a file on the local system, but it won't work for setting the media source to a file on the network. To do this, create a Uri object for the media file path and set the MediaElement.Source to it.

It's good practice to catch exceptions around the code that sets the media source.

Find it in the sample: Look at the AppBarTextBoxFilePath_KeyUp and SetMediaSourceFromPath methods in MainPage.xaml.cs. Look also at the appBarTextBoxFilePathTextBlock in the XAML in MainPage.xaml, which is used to enter the media path.

 

Media playback features

How to keep the display on during audio and video playback

Typically, when a Windows Store app does not detect user input within a certain period of time, the screen dims and eventually turns off. In most apps this is a good thing, because it conserves energy and battery life. In many media apps, though, we don't want the display to dim because someone is probably watching the video.

Use the System.Windows.Display.DisplayRequest class to tell the system to always keep the display on for your app. But be sure to cancel this request as soon as your app no longer needs it, such as when your app is suspending, the media is finished playing, or the media is paused. Not canceling this request wastes battery life.

If full-window rendering is enabled through the full-window button on the new MediaElement transport controls or through the IsFullWindow property, the system automatically handles disabling and re-enabling screen dimming. So if your app needs to disable screen dimming only in full-window mode, you do not need to manage the DisplayRequest yourself.

Find it in the sample: See the DisableScreenDimming and UpdateMediaState methods in MainPage.xaml.cs.

How to use the system media transport controls

Windows 8.1 introduces a new class for interacting with the system media transport controls. From now on, use SystemMediaTransportControls instead of the old MediaControl class.

The system media transport controls are different from the transport controls on the MediaElement object. These are the controls that pop up when hardware media keys, such as the volume control on a pair of headphones or the media buttons on some keyboards, are pressed. Your app can register to use these controls and can even pass back media metadata, such as album art or song titles, to be displayed by them.

Here's a look at the controls.

Find it in the sample: See the MainPage constructor, and the systemControls_ButtonPressed and UpdateMediaState methods in MainPage.xaml.cs.

How to play audio in the background.

Now let's set up background audio support, so users can listen to music with your app while interacting with a different app.

When an app playing audio is moved to the background, such as when the user switches to a different app, the default behavior is for the audio to stop. But a music app can choose to have the audio continue to play.

To play audio in the background you must set the background audio task in the app manifest Declarations. And you must enable the IsPlayEnabled and IsPauseEnabled properties on the SystemMediaTransportControls and handle the ButtonPressed event. This is required so the user has a way to play and stop the audio when your app is not the active app.

Find it in the sample: See the MainPage constructor and the EnableBackGroundAudio and systemControls_ButtonPressed methods in MainPage.xaml.cs. Finally, also look at the Declarations section of Package.appmanifest.xml for enabling the background task.

How to resize and stretch video

The MediaElement.Stretch property defines how the MediaElement fills the space of the container it's in. The Stretch states are similar to picture-size settings on many television sets. You can hook this property up to a UI button and let users choose the settings 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.

Here are examples of how these stretch values affect video rendering.

Find it in the sample: See the PictureSize_Click method in MainPage.xaml.cs.

How to enable full-window rendering

The built-in transport controls for the MediaElement class have a full-window button. But if you want to enable or disable full-window rendering programmatically, use the new IsFullWindow property.

Before Windows 8.1, you had to calculate the bounds of the full window, and show and hide the other UI yourself. If this isn't done in the right way, some rendering optimizations might not be enabled. So always use the IsFullWindow property to enable and disable full-window rendering. And it's easier.

Find it in the sample: See the ToggleFullWindow method in MainPage.xaml.cs.

How to create custom transport controls

If you need to expand on the functionality that the MediaElement transport controls provide, or if you want to replace them completely, you'll have to create custom transport controls. The Media playback, start to finish sample implements all the custom transport controls on the AppBar but leaves the built-in transport controls enabled on the MediaElement. If you are creating your own custom transport controls, you might prefer to simply replace the built-in UI with your own.

To turn off the built-in transport controls, set AreTransportControlsEnabled to false.

This how-to topic covers creating custom transport controls for play, pause, stop, fast forward, rewind, position slider, full window, audio section, mute, and volume.

Find it in the sample: See the <Page.BottomAppBar> element in MainPage.xaml, and see MainPage.xaml.cs for the event handlers that implement the features. The custom control to implement the timeline position slider is the majority of the code and is all at the end of MainPage.xaml.cs.

 

App basics

Adding app bars

Place UI that interacts with the app and the MediaElement on the AppBar. The AppBarButton and AppBarToggleButton controls are built specifically for the AppBar and work great.

The Symbol class contains a large number of symbols that you can use for the AppBarButton.Icon. You can also supply your own icon or use one from the Segoe UI Symbol icon list. All of the buttons in the companion sample use icons from Symbol.

Here's what the bottom AppBar looks like on the companion sample.

The companion sample groups some related feature in a Flyout, such as the image and audio buttons. This helps saves space.

For info about using the AppBar and designing your app, see Guidelines for app bars.

Find it in the sample: See MainPage.xaml and the <Page.TopAppBar> and <Page.BottomAppBar>. If you want to know how a particular control and feature is implemented, look at the event handlers for the app bar buttons in MainPage.xaml.cs.

Animating your UI

Animation can add a little pizzaz to your app. Even subtle animations will make your app stand out. Basic animations are simple to create, and the system provides a number of built-in transition animations.

The Media playback, start to finish sample creates a simple fade animation on text messages. It uses a Storyboard and DoubleAnimation on the Opacity property of the TextBlock. This causes the text to fade away after a few seconds.

Transition animations like EntranceThemeTransition can give visual cues that the state of your app has changed. The companion app uses an EntranceThemeTransition on some of the AppBarButton objects to give them a little bit of motion when the app bar opens.

Performance note: Don't animate the actual MediaElement object. This can have a negative impact on performance.

Find it in the sample: See the <Page.Resources> in MainPage.xaml and the DisplayMessage method in MainPage.xaml.cs.

Manage app lifecycle and state

Saving your app state in Windows Store apps is important, because your app can be suspended to the background at any time and terminated by the system. When your app resumes, the user will expect the media to be at the same place as before and all the app settings to be intact.

You can save the app state to the isolated storage on the device or to roaming storage. Roaming storage is nice because it lets the user run your app on multiple devices and the state will be shared between all of them.

Important MediaElement states to save are the Source, Position, Stretch, IsLooping, CurrentState, AutoPlay, and AudioStreamIndex.

SuspensionManager.cs and NavigationHelper.cs are helper classes that are part of the Visual Studio templates. They are included in all but the blank template. If you create a blank template, Visual Studio automatically adds these files if you add a new Basic item to your project. These helper classes simplify the handling of suspend, resume, and resume from termination. See the LoadState and SaveState methods in NavigationHelper.cs.

Some MediaElement state should be restored in the MediaOpen event handler, such as MediaElement.Position. This is because the media must be loaded before these properties can be set. For example, NaturalDuration is set after the media is loaded and the Position property cannot be greater than NaturalDuration, so you must set the Position after NaturalDuration is set.

Find it in the sample: See the navigationHelper_LoadState, navigationHelper_SaveState, Media_MediaOpened, and RestoreMediaSourceState methods in MainPage.xaml.cs. In App.xaml.cs look at the App constructor, OnLaunched, and OnSuspending for the SuspensionManager setup and suspend code.

Guidelines for app settings

Windows 8.1 introduces a SettingsFlyout control for Windows Store apps using C++, C#, or Visual Basic. SettingsFlyout simplifies creation of settings pages.

Settings are for configuration options that affect the behavior of the app as a whole and that are adjusted only occasionally. The Media playback, start to finish sample creates an Audio settings and Video Settings flyout that can be used to store app settings.

Find it in the sample: Look in the OnLaunched and OnCommandsRequested methods in App.xaml.cs for setup. And each Settings flyout has a corresponding Show method in App.xaml.cs, such as ShowAudioSettingsFlyout. The AudioSettings.xaml, VideoSettings.xaml, HelpSettings.xaml, and PrivacySettings.xaml flyouts are in the Settings subfolder.

 

Finish up

Using the Windows App Certification Kit

Recommended. Running the Windows App Certification Kit helps you make sure that your app fulfills Windows Store requirements. We recommend you run it whenever you add major functionality to your app.

You’re finished! Now that you’ve explored different media playback features for your app, you're ready to create an app like the Media playback, start to finish sample.

 

Want to know more?

Windows Store app UI, start to finish (XAML)

Learn more about designing Windows Store app UI.

User interaction, start to finish (XAML) and User interaction customization, start to finish (XAML)

Learn more about adding touch input to Windows Store apps.

Roadmap for Windows Runtime apps using C# and Visual Basic and Roadmap for Windows Runtime apps using C++

Learn more about creating apps in general.

Designing UX for apps

Learn more about designing great user experiences.

Supported audio and video formats

Learn more about supported audio and video formats in Windows Store apps using C++, C#, or Visual Basic.

Optimize media resources

Learn more about performance considerations for media apps.

Quickstart: adding controls and handling events

Learn more about controls and events in Windows Store app using C++, C#, or Visual Basic.