In this article, I will provide a walkthrough to "Play Background Audio" in Mango or a Windows 7.1 phone. This article is fully based on the Beta version and you will see how to play local media.
Step 1: Firstly, let us create a Windows Phone Application. To create it, open Visual Studio and select Windows Phone Application from the installed templates.

Since Background Audio playing is a feature of 7.1 version, do not forget to select Windows Phone 7.1 as the Target Version.

Step 2:
The next step we need to do is to add a project for Audio Playback Agent. So, right-click the solution and add a new project and from installed templates select Windows Phone Audio Playback Agent project type.

After adding this project, you will have two projects in the Solution Explorer. One is an Audio Playback Agent and another is the Phone Application.

Step 3:
Since both the projects have been created, now add a few music files to play. To do this right-click on AudioPlaybackAgent project and create a new folder. Give desired name to this folder. In this case, I am naming the newly created folder Music.
Right-click on the Music folder and add existing items. Add music files to this folder.

After adding Music files select all the Music files, right-click and open Properties:

In the Properies windows you need to change Copy to Output Directory property to Copy if newer:

Step 4:
By now, music resources are added. Now you need to create a representation class for the songs track. Right-click on AudioPlaybackAgent project and add a class. Give a desired name.

Track.cs
- using System;
- namespace AudioPlaybackAgent1
- {
- public class Track
- {
- public Uri Source
- {
- get;
- set;
- }
- public string Artist
- {
- get;
- set;
- }
- public string Title
- {
- get;
- set;
- }
- public string Album
- {
- get;
- set;
- }
- public Track(Uri source, string artist, string title, string album)
- {
- Source = source;
- Artist = artist;
- Title = title;
- Album = album;
- }
- }
- }
Step 5: Let us add required functionalities or modify default functionalities to perform various operations on an Audio file.
Returning List of SongsFirstly, you need to return a list of songs. To return a list of songs use GetSongs() in the AudioPlayer.cs class:

The above function is returning a list of Tracks.
To track the record number add a class level global variable. Let us say we have added:
Playing Song
Now we need to add a function to play a song. Create a function called Play.

As Input parameter pass a BackGroundAudioPlayer object.
Create a Track to play. As a parameter you need to pass the source of the track, title, artist and album name.
After creation of the Track call the Play () method on the BackgroundAudioPlayer object.
Playing Next Song
To play the next song we need to track the current track record and increase it by 1. Once it is equal to the total number of songs in the list reinitialize it to 0.

Playing Previous Song
To play the previous song we need to track the current track record and decrease it by 1. Once it is less than 0 then reinitialize it to the maximum number of songs in the list.

Handling User actions
We need to handle user actions like Play, Stop, and Pause etc. For that we need to modify the overridden function on UserAction. Add the following switch case in the on UserAction method.

Handling Play state changes
To handle Play state changes add the following switch case in the OnPlayStateChanged() overridden method.

Finally, after adding all the required functions and making all modifications to the AudioPlayer.cs class it would look like below:
AudioPlayer.cs
- using System;
- using Microsoft.Phone.BackgroundAudio;
- using System.Collections.Generic;
- namespace AudioPlaybackAgent1
- {
- public class AudioPlayer: AudioPlayerAgent
- {
- static int CurrentTrackPlaying = 0;
- /// <summary>
- /// Called when the playstate changes, except for the Error state (see OnError)
- /// </summary>
- /// <param name="player">The BackgroundAudioPlayer</param>
- /// <param name="track">The track playing at the time the playstate changed</param>
- /// <param name="playState">The new playstate of the player</param>
- /// <remarks>
- /// Play State changes cannot be cancelled. They are raised even if the application
- /// caused the state change itself, assuming the application has opted-in to the callback
- /// </remarks>
- protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) {
- base.OnPlayStateChanged(player, track, playState);
- //TODO: Add code to handle play state changes
- switch (playState)
- {
- case PlayState.TrackEnded:
- PlayNext(player);
- break;
- }
- NotifyComplete();
- }
- /// <summary>
- /// Called when the user requests an action using system-provided UI and the application has requesed
- /// notifications of the action
- /// </summary>
- /// <param name="player">The BackgroundAudioPlayer</param>
- /// <param name="track">The track playing at the time of the user action</param>
- /// <param name="action">The action the user has requested</param>
- /// <param name="param">The data associated with the requested action.
- /// In the current version this parameter is only for use with the Seek action,
- /// to indicate the requested position of an audio track</param>
- /// <remarks>
- /// User actions do not automatically make any changes in system state; the agent is responsible
- /// for carrying out the user actions if they are supported
- /// </remarks>
- protected override void OnUserAction(BackgroundAudioPlayer player, AudioTrack track, UserAction action,
- object param)
- {
- base.OnUserAction(player, track, action, param);
- switch (action)
- {
- case UserAction.Play:
- Play(player);
- break;
- case UserAction.Pause:
- player.Pause();
- break;
- case UserAction.Stop:
- player.Stop();
- break;
- case UserAction.FastForward:
- player.FastForward();
- break;
- case UserAction.Rewind:
- player.Rewind();
- break;
- case UserAction.SkipPrevious:
- PlayBack(player);
- break;
- case UserAction.SkipNext:
- PlayNext(player);
- break;
- case UserAction.Seek:
- player.Position = (TimeSpan) param;
- break;
- }
- //TODO: Add code to handle user actions through the application and system-provided UI
- NotifyComplete();
- }
- /// <summary>
- /// Called whenever there is an error with playback, such as an AudioTrack not downloading correctly
- /// </summary>
- /// <param name="player">The BackgroundAudioPlayer</param>
- /// <param name="track">The track that had the error</param>
- /// <param name="error">The error that occured</param>
- /// <param name="isFatal">If true, playback cannot continue and playback of the track will stop</param>
- /// <remarks>
- /// This method is not guaranteed to be called in all cases. For example, if the background agent
- /// itself has an unhandled exception, it won't get called back to handle its own errors.
- /// </remarks>
- protected override void OnError(BackgroundAudioPlayer player, AudioTrack track, Exception error, bool isFatal)
- {
- base.OnError(player, track, error, isFatal);
- //TODO: Add code to handle error conditions
- NotifyComplete();
- }
- /// <summary>
- /// Called when the agent request is getting cancelled
- /// </summary>
- protected override void OnCancel()
- {
- base.OnCancel();
- NotifyComplete();
- }
- private List < Track > GetSongs()
- {
- List < Track > lstSongs = new List < Track > ()
- {
- new Track(new Uri("TujheBhulaDia.mp3", UriKind.Relative),
- "Ranveer Kapoor and Priyanka Chopra",
- "Tumhe Bhula Dia",
- "Anajana Anjani"),
- new Track(new Uri("AasPassKhuda.mp3", UriKind.Relative),
- "Ranveer Kapoor and Priyanka Chopra",
- "Aas Paass Khuda",
- "Anajana Anjani"),
- new Track(new Uri("AnajanAnajni.mp3", UriKind.Relative),
- "Ranveer Kapoor and Priyanka Chopra",
- "Anajana Anjani",
- "Anajana Anjani")
- };
- return lstSongs;
- }
- private void Play(BackgroundAudioPlayer player)
- {
- var songs = GetSongs();
- var currentTrack = songs[CurrentTrackPlaying];
- player.Track = new AudioTrack(currentTrack.Source,
- currentTrack.Title,
- currentTrack.Artist,
- currentTrack.Album,
- null);
- player.Play();
- }
- private void PlayNext(BackgroundAudioPlayer player)
- {
- var songsCount = GetSongs().Count;
- if (++CurrentTrackPlaying >= songsCount)
- {
- CurrentTrackPlaying = 0;
- }
- Play(player);
- }
- private void PlayBack(BackgroundAudioPlayer player)
- {
- var songsCount = GetSongs().Count;
- if (--CurrentTrackPlaying < 0)
- {
- CurrentTrackPlaying = songsCount - 1;
- }
- Play(player);
- }
- }
- }







Vignesh ManiPosted Mar 18, 2016, 4:52 PM
nice
Saillesh PawarPosted Mar 18, 2016, 8:12 AM
Appreciate your hard work, thanks for sharing
Mohammed IbrahimPosted Mar 18, 2016, 6:50 AM
NICE
Kirtan ParmarPosted Mar 18, 2016, 3:46 AM
good one...thanks for shaing