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( 
   "https://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.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was 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 Microsoft MVP.
This entry was posted in Background Agents, Essentials, Mango, Mini-Tutorial, Multitasking, WindowsPhone and tagged . Bookmark the permalink.

10 Responses to Background Audio

Comments are closed.