Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone...

28
Hands-On Lab Music Player Lab version: 1.0.0 Last updated: 7/6/2022 Page | 1 ©2011 Microsoft Corporation. All rights reserved.

Transcript of Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone...

Page 1: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Hands-On LabMusic PlayerLab version: 1.0.0

Last updated: 5/17/2023

Page | 1©2011 Microsoft Corporation. All rights reserved.

Page 2: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

OVERVIEW................................................................................................................................................. 3

EXERCISE.................................................................................................................................................. 4Task 1 – Adding the main UI and functionality....................................................................................4

Task 2 – Adding Button Controls........................................................................................................10

Task 3 – Copying music and image files to Isolated Storage..............................................................16

Task 4 – Adding and Implementing the Audio Playback Agent..........................................................17

SUMMARY................................................................................................................................................ 24

Page | 2©2011 Microsoft Corporation. All rights reserved.

Page 3: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Overview

In the original Windows® Phone operating system, we could create a music player but the application was not able to continue playing music while inactive.

As we will see during this lab, with Windows® Phone Codenamed Mango, an application is able to continue playing audio even while inactive. To do this, we will use the new Background Audio Player class in Microsoft.Phone.BackgroundAudio namespace.

This lab shows how to use background audio in your application using the new Windows® Phone Codenamed Mango API, by developing a Music Player that can become inactive and continue playing music.

Objectives

This lab will show you how to:

Use the BackgroundAudio class to play music even if your application is not active.

Implement a background agent in your application

Prerequisites

The following prerequisites will help you gain the most from this hands-on lab:

Microsoft Visual Studio 2010 or Microsoft Visual C# Express 2010, and the Windows® Phone Developer Tools available at http://go.microsoft.com/?linkid=9772716

Prior knowledge regarding development of Windows® Phone applications (If you are new to Windows® Phone 7 development, begin by reading http://msdn.microsoft.com/en-us/gg266499. This lab assumes you understand the basics and focuses on demonstrating background audio.)

Estimated completion time

Completing this lab should take between 20 and 40 minutes.

Page | 3©2011 Microsoft Corporation. All rights reserved.

Page 4: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Exercise

The starting point for this exercise is the solution located in the lab installation folder under the Source\Begin folder.

The solution contains a project with all the user interface (UI) elements we will use in this exercise and the model (Playlist and Track) we will work with. As you progress through the exercise, you will gradually wire up the user interface to the application logic.

Task 1 – Adding the main UI and functionality

In this task, we will work on the application’s main, and only, page and implement the event handlers for Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer in order to keep playing audio even if the application is not in the foreground.

1. Open the solution under the Source\Begin folder and examine the project.

2. Open the MainPage.xaml file.

3. Set the DataContext property of the page itself by adding the following attribute to the phone:PhoneApplicationPage element:

XAML

DataContext="{Binding RelativeSource={RelativeSource Self}}"

4. Locate the grid named ContentPanel and add the HorizontalAlignment attribute, setting it to Stretch.

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" HorizontalAlignment="Stretch">

5. Now add the following RowDefinitions and a new TextBlock. You can see that we use the new textblock to display the name of the active playlist. We will add a property to hold the active playlist later in the lab:

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" HorizontalAlignment="Stretch"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/>

Page | 4©2011 Microsoft Corporation. All rights reserved.

Page 5: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

</Grid.RowDefinitions>

<TextBlock Text="{Binding ActivePlaylist.Name}" FontSize="{StaticResource PhoneFontSizeExtraLarge}"/></Grid>

6. Add a new ListBox as seen in the code below. This listbox will display the list of available music tracks.

XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" HorizontalAlignment="Stretch">

<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/>

</Grid.RowDefinitions>

<TextBlock Text="{Binding ActivePlaylist.Name}" FontSize="{StaticResource PhoneFontSizeExtraLarge}"/>

<ListBox ItemsSource="{Binding ActivePlaylist.Tracks}" Grid.Row="1" x:Name="lstTracks" HorizontalContentAlignment="Stretch" Loaded="lstTracks_Loaded">

<ListBox.ItemTemplate><DataTemplate>

<Grid HorizontalAlignment="Stretch"><Grid.RowDefinitions>

<RowDefinition/><RowDefinition/><RowDefinition/>

</Grid.RowDefinitions><Grid.ColumnDefinitions>

<ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/>

</Grid.ColumnDefinitions>

<Image Margin="10,0" Source="{Binding Tile, TargetNullValue={StaticResource NoArt}}" Grid.RowSpan="3" Width="60" Stretch="Uniform" VerticalAlignment="Center"/>

<TextBlock Text="{Binding Title}" Grid.Column="1" FontSize="{StaticResource PhoneFontSizeLarge}"/>

<TextBlock Text="{Binding Artist}" Grid.Row="1" Grid.Column="1"/>

<TextBlock Text="{Binding Album}" Grid.Row="2" Grid.Column="1"/>

</Grid></DataTemplate>

</ListBox.ItemTemplate>

Page | 5©2011 Microsoft Corporation. All rights reserved.

Page 6: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

</ListBox></Grid>

7. Open the file named MainPage.xaml.cs. This is the code behind file for the main page.

8. Add an empty method called lstTracks_Loaded as seen below:

C#

public partial class MainPage : PhoneApplicationPage{

...private void lstTracks_Loaded(object sender, RoutedEventArgs e){}...

}

9. Compile and run the application on the emulator. At this stage, you should see the following screen.

Figure 1

Page | 6©2011 Microsoft Corporation. All rights reserved.

Page 7: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

The application without an actual playlist.

10. Let us add the active playlist property we used for binding in the previous steps. Add a Playlist dependency property as seen below and call it ActivePlaylist:

C#

public partial class MainPage : PhoneApplicationPage{

public Playlist ActivePlaylist{

get { return (Playlist)GetValue(ActivePlaylistProperty); }set { SetValue(ActivePlaylistProperty, value); }

}

public static readonly DependencyProperty ActivePlaylistProperty =

DependencyProperty.Register("ActivePlaylist", typeof(Playlist), typeof(MainPage), new PropertyMetadata(null));

...}

11. Override the OnNavigatedTo method on the page in order to deploy the playlist supplied as one of the application’s resources to isolated storage.

C#

public partial class MainPage : PhoneApplicationPage{

...protected override void

OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){

Stream playlistStream = Application.GetResourceStream(new Uri("Misc/Playlist.xml", UriKind.Relative)).Stream;

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Playlist));

ActivePlaylist = (Playlist)serializer.Deserialize(playlistStream);

using ( IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication() )

{using ( IsolatedStorageFileStream file =

isoStorage.OpenFile("playlist.xml", FileMode.OpenOrCreate) ){

var writer = new StreamWriter(file);

Page | 7©2011 Microsoft Corporation. All rights reserved.

Page 8: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

serializer.Serialize(writer, ActivePlaylist);

}}

base.OnNavigatedTo(e);

}...

}

12. In the page’s constructor, add the following highlighted code snippet to subscribe to the PlayStateChanged event:

C#

public partial class MainPage : PhoneApplicationPage{

...public MainPage(){

InitializeComponent();

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

}...

}

13. Add the event handler function specified in the previous step along with some additional methods. This will update the track number of the currently playing track whenever the background audio player, which we use to play back tracks, changes its playback state:

C#

public partial class MainPage : PhoneApplicationPage{

...private void Instance_PlayStateChanged(object sender, EventArgs

e){

UpdateSelection();}

private void UpdateSelection(){

int activeTrackNumber = GetActiveTrackIndex();

if ( activeTrackNumber != -1 )

Page | 8©2011 Microsoft Corporation. All rights reserved.

Page 9: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

{lstTracks.SelectedIndex = activeTrackNumber;

}}

private int GetActiveTrackIndex(){

int track = -1;if ( null != BackgroundAudioPlayer.Instance.Track ){

track = int.Parse(BackgroundAudioPlayer.Instance.Track.Tag);

}

return track;}...

}

14. The background audio player will allow the user to change the actively playing track even while the application is not active. To handle this, update the lstTracks_Loaded method inserting the following code into that method:

C#

public partial class MainPage : PhoneApplicationPage{

...private void lstTracks_Loaded(object sender, RoutedEventArgs e){

UpdateSelection();}...

}

15. Compile and run the application. At this stage the main page should look like the following:

Page | 9©2011 Microsoft Corporation. All rights reserved.

Page 10: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Figure 2Playlist

16. Stop the debugging and return to the code.

17. This step concludes the current task.

Task 2 – Adding Button Controls

This step will explain how to add ApplicationBar buttons, which we will use to control the player. We will add four buttons: play, stop, previous and next track.

These buttons' functions will use services exposed by the BackgroundAudioPlayer class.

1. Open the MainPage.xaml file, if it is not already opened.

2. After the LayoutRoot grid ends, instead of the commented use of PhoneApplicationPage.ApplicationBar, add the following code:

XAML

Page | 10©2011 Microsoft Corporation. All rights reserved.

Page 11: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

<phone:PhoneApplicationPage.ApplicationBar> <shell:ApplicationBar IsVisible="True" IsMenuEnabled="False"> <shell:ApplicationBarIconButton IconUri="/Images/prev.png" Text="prev" Click="appbar_prev"/> <shell:ApplicationBarIconButton IconUri="/Images/play.png" Text="play" Click="appbar_playpause"/> <shell:ApplicationBarIconButton IconUri="/Images/stop.png" Text="stop" Click="appbar_stop"/> <shell:ApplicationBarIconButton IconUri="/Images/next.png" Text="next" Click="appbar_next"/> </shell:ApplicationBar></phone:PhoneApplicationPage.ApplicationBar>

3. Open the file MainPage.xaml.cs and add the handlers for the newly inserted buttons.

C#

public partial class MainPage : PhoneApplicationPage{

...#region ApplicationBar Buttons Eventsprivate void appbar_prev(object sender, EventArgs e){

BackgroundAudioPlayer.Instance.SkipPrevious();}

private void appbar_playpause(object sender, EventArgs e){

if ( BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing )

BackgroundAudioPlayer.Instance.Pause();else

BackgroundAudioPlayer.Instance.Play();}

private void appbar_stop(object sender, EventArgs e){

BackgroundAudioPlayer.Instance.Stop();}

private void appbar_next(object sender, EventArgs e){

BackgroundAudioPlayer.Instance.SkipNext();}#endregion...

}

Page | 11©2011 Microsoft Corporation. All rights reserved.

Page 12: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

4. Just as we updated the selected track in the previous task, we need to update the appbar buttons according to the player’s state. To do that, locate the Instance_PlayStateChanged method and add a call to UpdateAppBarStatus method.

C#

public partial class MainPage : PhoneApplicationPage{

...private void Instance_PlayStateChanged(object sender, EventArgs

e){

UpdateAppBarStatus();UpdateSelection();

}...

}

5. Now add the UpdateAppBarStatus method itself:

C#

public partial class MainPage : PhoneApplicationPage{

...private void UpdateAppBarStatus(){

switch ( BackgroundAudioPlayer.Instance.PlayerState ){

case PlayState.Playing://Prev Buttonif ( GetActiveTrackIndex() > 0 )

( ApplicationBar.Buttons[0] as ApplicationBarIconButton ).IsEnabled = true;

else( ApplicationBar.Buttons[0] as

ApplicationBarIconButton ).IsEnabled = false;

//Play/Pause Button( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IsEnabled = true;( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).Text = "pause";( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IconUri = new Uri("/Images/pause.png", UriKind.Relative);

//Stop Button( ApplicationBar.Buttons[2] as

ApplicationBarIconButton ).IsEnabled = true;

Page | 12©2011 Microsoft Corporation. All rights reserved.

Page 13: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

//Next buttonif ( GetActiveTrackIndex() <

ActivePlaylist.Tracks.Count - 1 )( ApplicationBar.Buttons[3] as

ApplicationBarIconButton ).IsEnabled = true;else

( ApplicationBar.Buttons[3] as ApplicationBarIconButton ).IsEnabled = false;

break;

case PlayState.Paused://Prev Buttonif ( GetActiveTrackIndex() > 0 )

( ApplicationBar.Buttons[0] as ApplicationBarIconButton ).IsEnabled = true;

else( ApplicationBar.Buttons[0] as

ApplicationBarIconButton ).IsEnabled = false;

//Play/Pause Button( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IsEnabled = true;( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).Text = "play";( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IconUri = new Uri("/Images/play.png", UriKind.Relative);

//Stop Button( ApplicationBar.Buttons[2] as

ApplicationBarIconButton ).IsEnabled = true;

//Next buttonif ( GetActiveTrackIndex() <

ActivePlaylist.Tracks.Count - 1 )( ApplicationBar.Buttons[3] as

ApplicationBarIconButton ).IsEnabled = true;else

( ApplicationBar.Buttons[3] as ApplicationBarIconButton ).IsEnabled = false;

break;

case PlayState.Stopped://Prev Buttonif ( GetActiveTrackIndex() > 0 )

( ApplicationBar.Buttons[0] as ApplicationBarIconButton ).IsEnabled = true;

else

Page | 13©2011 Microsoft Corporation. All rights reserved.

Page 14: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

( ApplicationBar.Buttons[0] as ApplicationBarIconButton ).IsEnabled = false;

//Play/Pause Button( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IsEnabled = true;( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).Text = "play";( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IconUri = new Uri("/Images/play.png", UriKind.Relative);

//Stop Button( ApplicationBar.Buttons[2] as

ApplicationBarIconButton ).IsEnabled = false;

//Next buttonif ( GetActiveTrackIndex() <

ActivePlaylist.Tracks.Count - 1 )( ApplicationBar.Buttons[3] as

ApplicationBarIconButton ).IsEnabled = true;else

( ApplicationBar.Buttons[3] as ApplicationBarIconButton ).IsEnabled = false;

break;

case PlayState.Unknown://Prev Button( ApplicationBar.Buttons[0] as

ApplicationBarIconButton ).IsEnabled = false;

//Play/Pause Button( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IsEnabled = true;( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).Text = "play";( ApplicationBar.Buttons[1] as

ApplicationBarIconButton ).IconUri = new Uri("/Images/play.png", UriKind.Relative);

//Stop Button( ApplicationBar.Buttons[2] as

ApplicationBarIconButton ).IsEnabled = false;

//Next buttonif ( GetActiveTrackIndex() <

ActivePlaylist.Tracks.Count - 1 )( ApplicationBar.Buttons[3] as

ApplicationBarIconButton ).IsEnabled = true;

Page | 14©2011 Microsoft Corporation. All rights reserved.

Page 15: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

else( ApplicationBar.Buttons[3] as

ApplicationBarIconButton ).IsEnabled = false;break;

default:

break;}

}...

}

6. Compile and run the application. At this stage the main page should look like the following:

Figure 3Playlist with playback controls

7. Stop the debugging and return to the code.

Page | 15©2011 Microsoft Corporation. All rights reserved.

Page 16: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Task 3 – Copying music and image files to Isolated Storage

In order to play the tracks we have in the solution, we need to copy these files to Isolated Storage.

1. Open the file named App.xaml.cs and add the following using directives:

C#

using System.IO.IsolatedStorage;using System.Windows.Resources;

2. At the constructor for the App class, add the following highlighted code:

C#

public App(){

...CopyToIsolatedStorage();

}

3. Now use the following code to add the CopyToIsolatedStorage method itself:

C#

private void CopyToIsolatedStorage(){

using ( IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication() )

{string[] files = new string[] { "file1.mp3", "file2.mp3",

"file3.mp3" };

foreach ( var _fileName in files ){

if ( !storage.FileExists(_fileName) ){

string _filePath = "Music/" + _fileName;StreamResourceInfo resource =

Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

using ( IsolatedStorageFileStream file = storage.CreateFile(_fileName) )

{int chunkSize = 4096;byte[] bytes = new byte[chunkSize];int byteCount;

while ( ( byteCount =

resource.Stream.Read(bytes, 0, chunkSize) ) > 0 )

Page | 16©2011 Microsoft Corporation. All rights reserved.

Page 17: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

{file.Write(bytes, 0, byteCount);

}}

}}

files = new string[] { "Image1.jpg", "Image3.jpg", "no-

art.jpg" };

foreach ( var _fileName in files ){

string _destFilePath = "Shared/Media/" + _fileName;;if ( !storage.FileExists(_destFilePath) ){

string _filePath = "Images/" + _fileName;StreamResourceInfo resource =

Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

using ( IsolatedStorageFileStream file = storage.CreateFile(_destFilePath) )

{int chunkSize = 4096;byte[] bytes = new byte[chunkSize];int byteCount;

while ( ( byteCount =

resource.Stream.Read(bytes, 0, chunkSize) ) > 0 ){

file.Write(bytes, 0, byteCount);}

}}

}}

}

4. This step concludes the current task.

Task 4 – Adding and Implementing the Audio Playback Agent

The last thing we need to do is to implement an “Audio Playback Agent”. This is instantiated by the operating system to handle actions requested by the user. AudioPlayerAgent runs in the background and calls into an instance of the BackgroundAudioPlayer, which then calls into the Zune Media Queue to play the audio.

Page | 17©2011 Microsoft Corporation. All rights reserved.

Page 18: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

1. Add a new project to the solution using the Windows Phone Audio Playback Agent template located under the Silverlight for Windows Phone category and name it AudioPlaybackAgent.

2. In this project, we will need to use the model defined in the Models project as well as XML serialization. Add references to both Models and System.Xml.Serialization.

3. Open the AudioPlayer.cs file created as part of the project and delete the entire contents of the AudioPlayer class.

4. Add the following using statements to the file:

C#

using System.IO.IsolatedStorage;using System.Xml.Serialization;using System.IO;using Models;

5. Add the following fields to the AudioPlayer class. These will be used to store the current playlist and keep track of the currently playing track:

C#

static int currentTrackNumber = 0;static Playlist playlist;

6. Add the following constructor, which will access the playlist XML file we took care to place in the application’s isolated storage:

C#

public AudioPlayer(): base()

{

//Load from IsoStore & deserialize using ( IsolatedStorageFile isoStorage = IsolatedStorageFile.GetU

serStoreForApplication() ){

using ( IsolatedStorageFileStream file = isoStorage.OpenFile("playlist.xml", FileMode.Open) )

{XmlSerializer serializer = new XmlSerializer(typeof(P

laylist));var reader = new StreamReader(file);

playlist = (Playlist)serializer.Deserialize(reader);}

}}

7. Add the following OnPlayStateChanged override, which handles changes in the agent’s playback status:

Page | 18©2011 Microsoft Corporation. All rights reserved.

Page 19: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

C#

protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState){

switch ( playState ){

case PlayState.TrackEnded:PlayNext(player);break;

case PlayState.TrackReady:player.Play();break;

default:break;

}

NotifyComplete();}

You can see that once a track ends we simply move on to the next track (using a method we will soon introduce) and that once a track is ready we simply use the background audio player to play it. The call to NotifyComplete is required to let the agent know that the state change was handled.

8. Add the following helper methods, which initiate playback of the next/previous track:

C#

private void PlayNext(BackgroundAudioPlayer player){

var songsCount = playlist.Tracks.Count;

if ( ++currentTrackNumber >= songsCount ){

currentTrackNumber = 0;}Play(player);

}private void PlayPrev(BackgroundAudioPlayer player){

var songsCount = playlist.Tracks.Count;if ( --currentTrackNumber < 0 ){

currentTrackNumber = songsCount - 1;}Play(player);

}

Page | 19©2011 Microsoft Corporation. All rights reserved.

Page 20: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

9. Add the following override for OnUserAction, to handle the various actions a user may perform when interacting with the audio playback agent:

C#

protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action, object param){

switch ( action ){

case UserAction.FastForward:player.FastForward();break;

case UserAction.Pause:player.Pause();break;

case UserAction.Play:if ( player.PlayerState == PlayState.Paused ){

player.Play();}else{

Play(player);}break;

case UserAction.Rewind:player.Rewind();break;

case UserAction.Seek:player.Position = (TimeSpan)param;break;

case UserAction.SkipNext:PlayNext(player);break;

case UserAction.SkipPrevious:PlayPrev(player);break;

case UserAction.Stop:player.Stop();break;

default:break;

}

NotifyComplete();}

10. Add an additional helper method for initiating playback of the current track, as dictated by the currentTrackNumber field we added previously:

Page | 20©2011 Microsoft Corporation. All rights reserved.

Page 21: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

C#

private void Play(BackgroundAudioPlayer player){

var currentTrack = playlist.Tracks[currentTrackNumber];Uri tileUri = ( currentTrack.Tile == null ? new Ur

i("Shared/Media/no-art.jpg", UriKind.Relative) :   ( 

currentTrack.Tile.IsAbsoluteUri ? new Uri("Shared/Media/no-art.jpg", UriKind.Relative) :

  new Uri(currentTrack.TileString.Replace("/Images", "Shared/Media"), UriKind.Relative) ) );

var audioTrack = new AudioTrack(currentTrack.Source,  currentTrack.Title,  currentTrack.Artist,  currentTrack.Album,  tileUri,  currentTrackNumber.To

String(),  EnabledPlayerControl

s.All);player.Track = audioTrack;

}

11. Add a pair of additional overrides for handling errors or cancellations, though we do not have any specific logic for such cases in this lab:

C#

protected override void OnCancel(){

NotifyComplete();}

protected override void OnError(BackgroundAudioPlayer player, AudioTrack track, Exception error, bool isFatal){

NotifyComplete();}

12. The last step is to add a reference to this new project from the MusicPlayer project.

13. Compile the application and make sure you do not get any errors.

14. Run the application. At this stage, the main page should be fully functional.

15. Now it is time to play some music. Click on the play ( ) button and be sure to turn the volume up (press F9 to increase the emulator’s own volume).

Page | 21©2011 Microsoft Corporation. All rights reserved.

Page 22: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Figure 4The fully functional application

16. Now you can navigate away from the application by pressing the Start Key ( ) and see that the music continues to play.

17. Pressing F9 to change the volume will reveal the current playback state, and you can control the current playing track just as you would through the application itself.

Page | 22©2011 Microsoft Corporation. All rights reserved.

Page 23: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Figure 5Controlling playback while the application is inactive

18. Change the currently track and launch the application again from the list of installed applications. The application should display the currently playing track correctly.

19. Stop the debugger.

20. This step concludes the current task and the entire lab.

Page | 23©2011 Microsoft Corporation. All rights reserved.

Page 24: Background Audio Agentsaz12722.vo.msecnd.net/.../MusicPlayer.docx · Web viewWindows Phone codenamed 'Mango' makes it possible for applications to continue playing audio even while

Summary

This lab has shown you how to use the new Windows® Phone Mango APIs to play music. You have also seen how to use this new API to develop an application that can play audio even while not in the foreground.

Page | 24©2011 Microsoft Corporation. All rights reserved.