Play Background Audio in Your Windows Phone Apps


Windows Phone Mango introduced support for a background audio feature, which makes it possible to have another application running in the foreground while the user continues listening to the latest musical sensation.

A Windows Phone application that plays Background Audio leverages the "background agents" feature. To build such an application, you can either implement it to play files or to stream. To build a streaming background audio application, you need to use the MediaStreamSource class (which resides in the System.Windows.Media namespace).


Media on the Windows Phone is played through the Zune Media Queue. To play content, the application needs to call method on the BackgroundAudioPlayer class, which interacts with the Zune Media Queue to play audio.


To start with, open Visual Studio and create a new Windows Phone application titled WPBackgroundAudioDemo. Click OK

Create a new Windows Phone application
Figure 1: Create a new Windows Phone application

When prompted, select Windows Phone OS 7.1 as the target OS and click OK.

Select the Windows Phone Platform
Figure 2: Select the Windows Phone Platform

Next, add a new Project of type "Windows Phone Audio Playback Agent" to the solution, titled AudioPlaybackAgentDemo.

Select a new Project of type bWindows Phone Audio Playback Agentb
Figure 3: Select a new Project of type "Windows Phone Audio Playback Agent"

Now, add reference to the AudioPlaybackAgentDemo project in your WPBackgroundAudioDemo project.

If you have some music files you want to play in your application, add them to your application. In this example, I have added "Lullabies.mp3" as a Content file.

Next, add a couple of buttons on the MainPage, one to start and one to stop the playback.

Now, open up the code-behind file for MainPage (MainPage.xaml.cs) and add the following code to include "Microsoft.Phone.BackgroundAudio" namespace to the page.

using Microsoft.Phone.BackgroundAudio;

Add code for the click events of the buttons we just added.

For the Start and Stop button's click event, the code is as below:

private void buttonStart_Click(object sender, RoutedEventArgs e)
            if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Playing )
        private void buttonStop_Click(object sender, RoutedEventArgs e)
            if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Stopped)

Next, create a helper function, which will copy our MP3 file to the isolated store (since Windows Phone platform only allows playing files from isolated storage).

private void SaveToIsoStore()
            IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
                StreamResourceInfo resource = Application.GetResourceStream(new Uri("Lullabies.mp3", UriKind.Relative));
                using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile("Lullabies.mp3"))
                    int chunkSize = 1024;
                    byte[] bytes = new byte[chunkSize];
                    int byteCount;
                    while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                        isolatedStorageFileStream.Write(bytes, 0, byteCount);

Now, in the constructor of the MainPage.xaml.cs, don't forget to call this helper function.

public MainPage()

Next, we add a new variable of type AudioTrack in the AudioPlayer class inside AudioPlayer.cs (from the AudioPlaybackAgentDemo project).

public class AudioPlayer : AudioPlayerAgent
        private static volatile bool _classInitialized;
        AudioTrack audioTrack = new AudioTrack(new Uri("Lullabies.mp3", UriKind.Relative), "Lullabies", "Bob Acri", "Bob Acri", null);
        /// <remarks>
        /// AudioPlayer instances can share the same process. 
        /// Static fields can be used to share state between AudioPlayer instances
        /// or to communicate with the Audio Streaming agent.
        /// </remarks>
        public AudioPlayer()

Note that we did this solely to illustrate in the example. If you are building an application, you should query your MP3 collection and get the properties and populate this information.

Finally, update the auto-generated code for OnUserAction method:

protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param)
            switch (action)
                case UserAction.Play:
                    if (player.PlayerState != PlayState.Playing)
                        player.Track = this.audioTrack;
                case UserAction.Stop:
                case UserAction.Pause:
                case UserAction.FastForward:
                case UserAction.Rewind:
                case UserAction.Seek:
                    player.Position = (TimeSpan)param;
                case UserAction.SkipNext:
                    player.Track = GetNextTrack();
                case UserAction.SkipPrevious:
                    AudioTrack previousTrack = GetPreviousTrack();
                    if (previousTrack != null)
                        player.Track = previousTrack;

Now, you are ready to compile and test the application.

When you run the application and click Start, you will notice that music is being played. Even when you navigate away from the application (for example, open the browser on the phone), you still hear music being played. This is background audio in action

If you are having trouble get the code to work, you can download a working sample of the code below.


In this article, we discussed how to build a Windows Phone application that plays background audio. I hope you have found this information useful.

This article was originally published on January 17th, 2012

About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Related Articles


Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date