Windows 8.1 makes it extremely easy to develop an app that plays audio in the background using low power. The Windows Runtime provides a standard set of minimal system controls that provide a consistent experience to the user when streaming audio. These controls appear briefly when the user manipulates an audio control (such as adjusting the volume), take up a small portion of the screen, and provide relevant data and a simple way to navigate through playlists.
The AudioBackgroundExample project under the Chapter15 solution folder demonstrates how to set up your app for background audio. The main elements of the app are no different from an app that only supports foreground audio. The XAML for the main page contains a standard MediaElement with simple controls to play, pause, and stop the audio stream. You can also use system-provided controls by setting the AreTransportControlsEnabled property to true.
One important step to prepare for background audio is to set the audio category:
MediaPlayer.AudioCategory = AudioCategory.BackgroundCapableMedia;
In addition to code that enables foreground playback, the remaining code in the example is required to support the background playback. The first step in enabling this is declaring the audio background task. This is done on the Declarations tab of the manifest UI. Add the Background Tasks declaration, check the Audio option and copy the entry point from the Application tab (the fully qualified name of your App class). Your app must keep track of the SystemMediaTransportControls instance that is provided by the Windows Runtime.
this.transportControls = SystemMediaTransportControls.GetForCurrentView();
You can then enable the control and various features within the control, and respond to button click events. The system transport controls are capable of displaying information about the currently playing track and an associated thumbnail. Although you can set these explicitly, the easiest way is to use the metadata associated with the file. If the file was downloaded from Xbox Music, for example, it will automatically have metadata including the artist name, song title, and a thumbnail of the album provided. An example of copying the metadata to the display is shown in the example app.
Whenever the user presses a button on the transport control, the registered TransportControlsButtonPressed handler is called. Because the audio is in the background, the button press is initiated from the Windows shell and will not arrive on the UI thread. Therefore, any updates must be marshalled using the Dispatcher. The handler will then call the same methods used by the buttons in the app’s own UI.