User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

    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
    (Full Size Image)
    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
    (Full Size Image)
    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 b�Windows Phone Audio Playback Agentb�
    (Full Size Image)
    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.

    Keywords: C#, MOBILE, .NET, WINDOWS PHONE 7, WP7,

    About the Author

    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

    Downloads

  • WPBackgroundAudioDemo.zip

  • IT Offers


    Top Authors