Background Audio

Windows Phone Tutorial

When you are playing audio in your application you may not want that audio to stop when the user switches to another application.  Windows Phone 7.5 (Mango) brings Background Audio using the BackgroundAudioPlayer.

In my previous post on Background Agents, I looked at the creation of a Periodic Task.  The process for creating Background Audio is surprisingly similar.  Once again you create a foreground project and then add a dedicated Audio Playback Agent project to the solution.  The Agent has once class: AudioPlayer, which manages changes to the state of the player and user actions. 

To get started, create a new Windows Phone application and name it whatever you like (I named mine Background Audio).  Set the Application Title to BACKGROUND AUDIO and remove the Page Title.  Add a Button and a TextBlock to the Content Panel, as shown in the following code,

         <StackPanel>
            <Button
            Content=">"
            Name="PlayButton"
            Height="140"
            Width="140"
               Click="PlayButton_Click" />
            <TextBlock
               Name="CurrentTrack"
               Height="150"
               Width="438"
               TextWrapping="Wrap" />
         </StackPanel>

 

Add a second project to the solution, using the Windows Phone Audio Playback Agent template.  Put a reference to the new project in the foreground project. 

Open MainPage.xaml.cs and register for the PlayStateChanged event on the Background Audio Player,

BackgroundAudioPlayer.Instance.PlayStateChanged += 
    new EventHandler( Instance_PlayStateChanged );

Implement the event handler to handle toggling between Play and Pause/Stop and to show the track title and artist,

void Instance_PlayStateChanged( object sender, EventArgs e )
{
    switch (BackgroundAudioPlayer.Instance.PlayerState)
    {
        case PlayState.Playing:
            PlayButton.Content = "||";
            break;
        case PlayState.Paused:
        case PlayState.Stopped:
            PlayButton.Content = ">";
            break;
    }

    if (BackgroundAudioPlayer.Instance.Track != null)
    {
        CurrentTrack.Text = 
            BackgroundAudioPlayer.Instance.Track.Title + " by " +
            BackgroundAudioPlayer.Instance.Track.Artist;
    }
}

 

The Play button has its event handler declared in the Xaml.  Implement the event handler now, which will toggle the PlayerState when the button is clicked,

private void PlayButton_Click( object sender, RoutedEventArgs e )
{
    if (PlayState.Playing == 
        BackgroundAudioPlayer.Instance.PlayerState)
    {
        BackgroundAudioPlayer.Instance.Pause();
    }
    else
    {
        BackgroundAudioPlayer.Instance.Play();
    }
}

Override the OnNavigatedTo method to handle restoring the UI when returning the page,

 protected override void OnNavigatedTo( 
     System.Windows.Navigation.NavigationEventArgs e )
 {
     if (BackgroundAudioPlayer.Instance.PlayerState == 
         PlayState.Playing)
     {
         PlayButton.Content = "||";
         CurrentTrack.Text = 
             BackgroundAudioPlayer.Instance.Track.Title 
             + " by " +
             BackgroundAudioPlayer.Instance.Track.Artist;
     }
     else
     {
         PlayButton.Content = ">";
         CurrentTrack.Text = string.Empty;
     }
 }

Open the AudioStreamer.cs file in the Audio Stream Agent project.  Scroll down to GetPreviousTrack and add the following lines of code (substitute your own favorite podcast as needed!)

AudioTrack track = new AudioTrack( 
   new Uri( 
   "http://jesseliberty.com/wp-content/media/Show47.mp3", 
    UriKind.Absolute ),
        "Show 47",
        "Yet Another Podcast",
        "Yet Another Podcast",
        null );

 

That’s it!  The templated code in AudioStreamer.cs takes care of the rest of the work of manipulating the player. 

You can also pass in the Uri of a local file, but that audio file must first be copied to Isolated Storage; a story for another day.

Share

About Jesse Liberty

Jesse Liberty is an independent consultant and programmer with three decades of experience writing and delivering software projects. He is the author of 2 dozen books and multiple Pluralsight courses, and has been a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP, Microsoft MVP and Telerik MVP.
This entry was posted in Background Agents, Essentials, Mango, Mini-Tutorial, Multitasking, WindowsPhone and tagged . Bookmark the permalink.

9 Responses to Background Audio

  1. You ought to be a part of a contest for one of the most useful blogs on the net.

    I most certainly will highly recommend this blog!

    my weblog; spanish pronunciation

  2. rickj1 says:

    Developing windows phone 8 on windows 8 is a nightmare you guys had something that worked what a mess

  3. Yama says:

    I know that background audio agent runs in different process. But how long does this process live?

  4. venkatasuresh says:

    is it possible to schedule sound in background task?

  5. Rodrigo says:

    I must create a new project Windows Phone Audio Streaming Agent as well? It’s not clear the following steps.

  6. dhay says:

    How to set up the track from the foreground project? because here, you add a new track in the GetPreviousTrack methode. How to add dynamically a track from the foreground project to the audio agent ?

  7. Anonymous9748 says:

    You need to be sure to include these ‘using’ statements:

    using System.Windows.Navigation;
    using Microsoft.Phone.BackgroundAudio;

  8. Brad Winborg says:

    I am just starting to do phone applications, so articals like this are a great help. Please keep them comming.

Leave a Reply

Your email address will not be published.