Play Background Audio in Windows 7.1 [Mango] Phone



In this article, I provide a walkthrough to "Play Background Audio" in Mango or a Window 7.1 phone. This article is fully based on the Beta version. In this article, I will show how to play local media.

Step 1

First let us create a Windows Phone Application. To create it, open Visual Studio and select Windows Phone Application from the installed templates.

AudWinPho1.gif

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

AudWinPho2.gif

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.

AudWinPho3.gif

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.

AudWinPho4.gif

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 new folder. Give desired name to this folder. In this case, I am naming the newly created folder as Music.

Right-click on the Music folder and add existing items. Add music files to this folder.

AudWinPho5.gif

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

AudWinPho6.gif

In the Property windows you need to change Copy to Output Directory Properties to Copy if newer:

AudWinPho7.gif

Step 4

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

AudWinPho8.gif

Track.cs

using System;
namespace AudioPlaybackAgent1
{
    public class Track
    {
 
        public Uri Source { getset; }
        public string Artist { getset; }
        public string Title { getset; }
        public string Album { getset; }
 
        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 Songs

First you need to return a list of songs. To return a list of songs use GetSongs() in the AudioPlayer.cs class:

AudWinPho9.gif

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:

AudWinPho10.gif

Playing Song

Now we need to add a function to play a song. Create a function called Play.

AudWinPho11.gif

  1. As Input parameter pass a BackGroundAudioPlayer object

  2. Create a Track to play. As a parameter you need to pass the source of the track, title, artist and album name.

  3. 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.

AudWinPho12.gif

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.

AudWinPho13.gif

Handling User actions

We need to handle user actions like Play, Stop, and Pause etc. For that you need to modify the overridden function onUserAction. Add the following switch case in the onUserAction method.

AudWinPho14.gif

Handling Play state changes

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

AudWinPho15.gif

Finally after adding all the required functions and making all modifications to the AudioPlyaer.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);
        }
    }
}

Step 6

Add a reference for the AudioPlaybackAgent1 project in the Phone Application project. For that right-click on Phone Application project and select Add Reference. In the dialog box choose the Projects tab and choose AudioPlaybackAgent1.

AudWinPho16.gif

Step 7

To play audio we have done all modification and added codes to AudioPlayBackAgent1 project. Now you need to create a UI in the Phone application project.
 
Create UI

  1. Add Three buttons for Play, Previous and Next

  2. Add a Text block to display Track information

MainPage.xaml

<phone:PhoneApplicationPage 
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">    
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>       
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Mango Background Audio Player" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Playing Song" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>      
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel Orientation="Horizontal" Width="420" Margin="18,40,18,0" VerticalAlignment="Top">
                <Button Content="prev" x:Name="prevButton" Height="140" Width="140" Click="prevButton_Click"/>
                <Button Content="play" x:Name="playButton" Height="140" Width="140" Click="playButton_Click"/>
                <Button Content="next" x:Name="nextButton" Height="140" Width="140" Click="nextButton_Click"/>
            </StackPanel>
            <TextBlock x:Name="txtCurrentTrack" Height="75" HorizontalAlignment="Left" Margin="12,193,0,0"
VerticalAlignment
="Top" Width="438" TextWrapping="Wrap" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage
>


After modifying the above code the user interface would look like:

AudWinPho17.gif

We need to handle click events. Very first add the following namespaces:

AudWinPho18.gif

And a click event for three buttons would be fairly straight forward.

AudWinPho19.gif

We need only to call SkipNext and SkipPrevious methods on instance of BackgroundAudioPlayer.

Handling Background player Play State changed event

First you need to register an event in the constructor of MainPage class. This event would check if playing track is not null then would display information in the text block.

AudWinPho20.gif

Handling user Navigation
 
Since audio would be playing in the background so when user will navigate should be displayed with meaningful information. For that you need to override OnNavigatedTo virtual method.

AudWinPho21.gif

After adding all required events eventually MainPage.xaml.cs will be as below:

MainPage.xaml.cs

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

namespace PhoneApp1
{
    public partial class MainPage : PhoneApplicationPage
    {
         public MainPage()
        {
            InitializeComponent();
          
            BackgroundAudioPlayer.Instance.PlayStateChanged += new EventHandler(Instance_PlayStateChanged);
            prevButton.Click += new RoutedEventHandler(prevButton_Click);
            nextButton.Click += new RoutedEventHandler(nextButton_Click);
            playButton.Click += new RoutedEventHandler(playButton_Click);
            
        }

         void Instance_PlayStateChanged(object sender, EventArgs e)
         {
             AudioTrack  tracks = BackgroundAudioPlayer.Instance.Track;
             if (tracks != null)
             {
                 txtCurrentTrack.Text = tracks.Title + " by " + tracks.Artist;
 
             }
         }
        void playButton_Click(object sender, RoutedEventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState )
            {
                BackgroundAudioPlayer.Instance.Pause();
                playButton.Content = "play";
 
            }
            else
            {
                BackgroundAudioPlayer.Instance.Play();
                playButton.Content = "pause";
 
            }
        }
        void nextButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipNext();
        }
 
        void prevButton_Click(object sender, RoutedEventArgs e)
        {
            BackgroundAudioPlayer.Instance.SkipPrevious();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
            {
                playButton.Content = "pause";
                txtCurrentTrack.Text = BackgroundAudioPlayer.Instance.Track.Title +
                                 " by " +
                                 BackgroundAudioPlayer.Instance.Track.Artist;
 
            }
            else
            {
                playButton.Content = "play";
                txtCurrentTrack.Text = "";
            }
        }
    }
}


Step 8

BackGroundAudioPlayer can only play a song from a remote URL or file in Isolated Storage. For that you need to add a function in App.Xaml.cs.

Adding music File to Isolated Storage

AudWinPho22.gif

In the above function the points to be noted are:

  1. Files name are exactly the same as you added in previous steps.

  2. The folder name is exactly the same.

  3. The sequence of File names in string array files is exactly the same as you are returning from GetSongs() method.

  4. Call this function in constructor of App class.

App.xaml.cs
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
 
 
namespace PhoneApp1
{
    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { getprivate set; }
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions. 
            UnhandledException += Application_UnhandledException;
 
            // Standard Silverlight initialization
            InitializeComponent();
 
            // Phone-specific initialization
            InitializePhoneApplication();
 
            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;
 
                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;
 
                // Enable non-production analysis visualization mode, 
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;
 
                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disable user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }
            CopyToIsolatedStorage();
 
        }
 
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }
 
        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }
 
        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }
        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }
 
        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }
 
        private void CopyToIsolatedStorage()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string[] files = new string[] { "TujheBhulaDia.mp3""AasPassKhuda.mp3""AnajanAnajni.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)
                            {
                                file.Write(bytes, 0, byteCount);
                            }
                        }
                    }
                }
            }
        }

        #region Phone application initialization
 
        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;
 
        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;
 
            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;
 
            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;
 
            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }
        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;
 
            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }
 
        #endregion
    }
}


Step 9

Now you have created a background music player. Press F5 to run the application.

AudWinPho23.gif

I hope this article was useful. Thanks for reading...

Up Next
    Ebook Download
    View all
    Learn
    View all