Windows Phone 8.1–Background Audio in Windows Phone Store apps

With the introduction of Windows Phone 8.1 you’ve the choice to either continue with the Windows Phone Silverlight 8.1 option or to use the Windows Phone Store Apps model similar to Windows 8 Store Apps.

However you can’t just upgrade to Windows Phone Silverlight 8.1 in every situation. Some features just aren’t supported in Silverlight 8.1, one of them being the AudioPlayerAgent which we use when implementing Background Audio in Windows Phone 8.

Upgrading to the Windows Phone Store Apps model isn’t an easy task either, the Background Audio is implemented in a completely different way. But there are reasons for people to do upgrade to the Windows Phone Store Apps model. One of these is the ability to change the speed of playback, an often requested feature for the P | Cast podcast app I created. Another option is to share a lot of the code by creating a Universal app which will enable both a Windows Store app and a Windows Phone Store app. I will not go into the details of the Background Audio for the Windows Store apps, but they are a little bit different compared to the implementation of the Background Audio in the Windows Phone Store apps. Different, but still similar though!

Alright, enough about the background, let’s start building a very basic app with Background Audio!

A little bit of architecture

We want to play audio which stays playing while our user interface isn’t active. So we need to have a background process that’s capable of playing audio. See the green blocks at the right in below diagram. The actual audio playback occurs in the background process while the foreground process has access to the MediaPlayer information via a Proxy Object.

Background Audio Architecture Windows Phone 8.1

To manage the Universal Volume Control, like the one below we’ll need to talk to the SystemMediaTransportControl. This API that also exists in Windows 8.1 so if we ever want to create a Universal App this will come in handy.

Universal Volume Control Windows Phone 8.1

But the actual communication between the foreground process aka the UI and the background process happens through messaging. You can pass messages from foreground to background, but also the other way around. A message consists of a string message, but can also pass an additional value (only simple value types).

Life Cycle of the Background Task

The Background Task is initiated the first time the Foreground Process does a call to BackgroundMediaPlayer.Current. Upon initiation the IBackgroundTask.Run is called.

You want the background audio to continue playing, so you have to get a BackgroundTaskDeferral in the Run method of the IBackgroundTask. You’ll have to complete the deferral upon the Canceled or Completed events of the task. The actual Run method should run to the end in a timely fashion, if it’s more or less waiting in the Run method the Background Task could be terminated to release resources.

The background task for running audio can be cancelled in a couple of situations:

  • When another app with audio playback starts
  • When the background task is running but no audio is playing (paused or never started) and the foreground app is suspended

The playback will be automatically paused by media interruptions like a phone call or VoIP call. When the phone call or VoIP call ends within 5 minutes, the background audio is resumed by executing the Run method and sending a ButtonPressed (PlayButton) event on the SystemMediaTransportControls instance. When the call takes longer than 5 minutes the playback doesn’t start but the Universal Volume Control doesn’t loose state and hitting the play button will restart the Background Audio manually.

Termination of the background task happens without warning when:

  • A VoIP call comes in and there is not enough memory
  • A resource policy is violated
  • Task cancellation or completion does not end gracefully

Project Setup

Besides the creation of a Windows Phone 8.1 app, it’s required to create a Windows Runtime Component (Windows Phone).

image

Add the BackgroundAudioTask which implement IBackgroundTask, like below. The details of the implementation will be filled in later.

public sealed class BackgroundAudioTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
            
    }
}

 

In the Windows Phone 8.1 App project you can add a reference to the Windows Runtime Component project. Please don’t make it a class library.

Go to the Package.appxmanifest to the Declarations tab and add a Background Task. Give it the the task type Audio and set the Entry point to the BackgroundAudioTask we created by using the full type name (namespace+type name).

image

The UI of the Player

Because I want to focus on the background audio, I made the UI simple, very simple. One Button, just the play button.

SNAGHTML4308a0c9

So the little bit of xaml that’s there to create a button with the click handler.

<Grid>
    <Button Content="Play" Click="PlayButtonClick"></Button>
</Grid>

We need the Background Task to fire up, so we have to access the BackgroundMediaPlayer.Current property. We do this in the OnNavigatedTo of the MainPage.

private MediaPlayer _mediaPlayer;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    _mediaPlayer = BackgroundMediaPlayer.Current;
}

 

And the PlayButtonClick is almost empty as well. We send a message to the background task. The message has a key indicating the operation Play, the value being a url to the background media we want to play. We will have to handle this in the background audio, but this is all we do in the UI.

private void PlayButtonClick(object sender, RoutedEventArgs e)
{
    var message = new ValueSet
                    {
                        {
                            "Play",
                            "http://media.ch9.ms/ch9/a092/c301b08c-1acc-4f2c-b636-61f4e917a092/3-159.mp3"
                        }
                    };
    BackgroundMediaPlayer.SendMessageToBackground(message);
}

Code a Background Task for Background Audio

After all the explanation above it’s time to write some real code. In the below piece of code you can see that all we do in the Run method is preparation. My advice to you is to keep this as short as possible as well. In line 3, we get a reference to the SystemMediaTransportControls, being the Universal Volume Control, and enable the Universal Volume Control.

In line 6 we subscribe to the receiving of the messages that are sent from the UI and line 7 does subscribe to the MediaPlayer state changes like Stopped, Playing and Paused.

To make sure the background task keeps running we get a deferral and also subscribe the Canceled and Completed events (line 10 – 13).

public void Run(IBackgroundTaskInstance taskInstance)
{
    _systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
    _systemMediaTransportControl.IsEnabled = true;
            
    BackgroundMediaPlayer.MessageReceivedFromForeground += MessageReceivedFromForeground;
    BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayerCurrentStateChanged;

    // Associate a cancellation and completed handlers with the background task.
    taskInstance.Canceled += OnCanceled;
    taskInstance.Task.Completed += Taskcompleted;

    _deferral = taskInstance.GetDeferral();
}

private SystemMediaTransportControls _systemMediaTransportControl;
private BackgroundTaskDeferral _deferral;

 

Let’s first make sure we handle the closing of the background task correctly. The implementation of playing music can wait a bit. Make sure that you save some state if required in the OnCanceled implementation before completing the deferral.

private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
    BackgroundMediaPlayer.Shutdown();
    _deferral.Complete();
}

private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
    // You get some time here to save your state before process and resources are reclaimed
    BackgroundMediaPlayer.Shutdown();
    _deferral.Complete();
}

 

Yes I know, now it’s time to implement the Play back code. Our UI did send a Message to the Background Audio Task, so we need to handle that message. The handling of the message happens in the MessageReceivedFromForeground method. We’re getting the ValueSet message as an argument and need to loop through the ValueSet keys to process the message. If we find a key with the value “Play” (line 8), we want to start the playback of the value passed to the message (line 10).

private void MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
{
    ValueSet valueSet = e.Data;
    foreach (string key in valueSet.Keys)
    {
        switch (key)
        {
            case "Play":
                Debug.WriteLine("Starting Playback");
                Play(valueSet[key].ToString());
                break;
        }
    }
}

 

The implementation isn’t that difficult, most of the code behind the Play method is the updating of the Universal Volume Control with the correct information. For the playing we set AutoPlay and the UriSource (lines 3-5).

private void Play(string toPlay)
{
    var mediaPlayer = BackgroundMediaPlayer.Current;
    mediaPlayer.AutoPlay = true;
    mediaPlayer.SetUriSource(new Uri(toPlay));

    //Update the universal volume control
    _systemMediaTransportControl.ButtonPressed += MediaTransportControlButtonPressed;
    _systemMediaTransportControl.IsPauseEnabled = true;
    _systemMediaTransportControl.IsPlayEnabled = true;
    _systemMediaTransportControl.DisplayUpdater.Type = MediaPlaybackType.Music;
    _systemMediaTransportControl.DisplayUpdater.MusicProperties.Title = "Test Title";
    _systemMediaTransportControl.DisplayUpdater.MusicProperties.Artist = "Test Artist";
    _systemMediaTransportControl.DisplayUpdater.Update();
}

 

Now we have audio playing, but the Universal Volume Control isn’t working completely yet. We need to make sure that PlaybackStatus of the SystemMediaTransportControl is reflecting the MediaPlayer state. The code is straightforward but needs to be there.

private void BackgroundMediaPlayerCurrentStateChanged(MediaPlayer sender, object args)
{
    if (sender.CurrentState == MediaPlayerState.Playing)
    {
        _systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Playing;
    }
    else if (sender.CurrentState == MediaPlayerState.Paused)
    {
        _systemMediaTransportControl.PlaybackStatus = MediaPlaybackStatus.Paused;
    }
}

 

The Universal Volume Control has buttons we need to handle as well. In this example we just handle the Play and Pause button, but you can think about implementing the Next and Previous buttons as well.

private void MediaTransportControlButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
    switch (args.Button)
    {
        case SystemMediaTransportControlsButton.Play:
            BackgroundMediaPlayer.Current.Play();
            break;
        case SystemMediaTransportControlsButton.Pause:
            BackgroundMediaPlayer.Current.Pause();
            break;
    }
}

 

Yes that was all. I know there’s quite a lot of preparations for getting the Background Audio working, but now we can expand this base into a fully fledged audio app.

You can download the full solution here.