Play Background Audio in Your Windows Phone Apps

Introduction

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

Architecture

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.

Hands-On

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 )
                BackgroundAudioPlayer.Instance.Play();
 
        }
 
        private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            if (BackgroundAudioPlayer.Instance.PlayerState != PlayState.Stopped)
                BackgroundAudioPlayer.Instance.Stop();
        }

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();
            if(!isolatedStorageFile.FileExists("Lullabies.mp3"))
            {
                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()
        {
            InitializeComponent();
            SaveToIsoStore();
        }

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;
                        player.Play();
                    }
                    break;
                case UserAction.Stop:
                    player.Stop();
                    break;
                case UserAction.Pause:
                    player.Pause();
                    break;
                case UserAction.FastForward:
                    player.FastForward();
                    break;
                case UserAction.Rewind:
                    player.Rewind();
                    break;
                case UserAction.Seek:
                    player.Position = (TimeSpan)param;
                    break;
                case UserAction.SkipNext:
                    player.Track = GetNextTrack();
                    break;
                case UserAction.SkipPrevious:
                    AudioTrack previousTrack = GetPreviousTrack();
                    if (previousTrack != null)
                    {
                        player.Track = previousTrack;
                    }
                    break;
            }
 
            NotifyComplete();
        }

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.

Summary

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



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

Downloads

Comments

  • How to set the audio track from the main page

    Posted by EngDev on 06/30/2013 01:17am

    I want to download audio and play that audio in background so the audio track not be in application resource it will save at application IsolatedStorage so i need to set the audio track at the application not AudioPlaybackAgentDemo

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • If you need new tools and tricks to make your meetings profitable and productive, then 5 Tips in 5 Minutes: A Quick Guide for More Profitable Sales Meetings is for you. Timely, practical tips that you can incorporate in just seconds will save you literally hours in travel and meeting time, not to mention help you to focus on what your sales prospects really want to know and how you can meet their needs. Get 5in5: A Quick Guide for More Profitable Sales Meetings and start building your sales the smarter, faster …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds