Walkthrough on Play Background Audio in Windows 7.1 [Mango] Phone

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

Step1

First let us create Windows Phone Application. To create, Open Visual Studio and select Windows Phone Application from installed template.

clip_image002

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

clip_image003

Step 2

Next step we need to do is to add a project for Audio Playback Agent. So right click to the solution and Add new project and from installed templates select Windows Phone Audio Playback Agent project type.

clip_image005

After adding this project, you would have two projects in solution explorer. One Audio Player Back Agent and another is Phone Application

clip_image006

 

Step 3

Since both the projects have been created, now add few music files to play. To do this right clicks on AudioPlaybackAgent project and new folder. Give desired name to this folder. In this case, I am naming newly created folder as Music.

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

clip_image007

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

clip_image008

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

clip_image009

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 .

clip_image011

 

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 Audio file.

Returning List of Songs

First you need to return List of songs. To return list of songs GetSongs() in AudioPlayer.cs class

clip_image013

Above function is returning List of Tracks.

To track the record number adds a class level global variable. Let us say we have added

clip_image014

 

Playing Song

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

 

clip_image016

  1. As Input parameter pass BackGroundAudioPlayer object
  2. Create a Track to play. As parameter you need to pass Source of the track, title, artist and album name.
  3. After creation of Track call Play () method on object of BackgroundAudioPlayer.

Playing Next Song

To play next song we need to track the current track record and increase it by 1. Once it is equal to total number of songs in list reinitialized it to 0.

clip_image018

Playing Previous Song

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

clip_image020

Handling User actions

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

clip_image021

 

Handling Play state changes

To handle Play state changes add below switch case in OnPlayStateChanged() overwritten method.

clip_image022

Finally adding all the required functions and modification AudioPlyaer.cs class 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 5

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

clip_image024

Step 6

To play audio we have done all modification and added codes to AudioPlayBackAgent1 project. Now you need to create a UI in 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 above code user interface would look like

clip_image025

We need to handle click events. Very first add below namespace

 

clip_image026

 

 

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

 

clip_image028

We need only to call SkipNext , 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.

clip_image030

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.

clip_image032

 

After adding all required events eventually MainPage.xaml.cs 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 7

BackGroundAudioPlayer can only play song from 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

 

clip_image034

In above function points to be noted

  1. Files name are exactly same as you added in previous steps
  2. Folder name is exactly the same.
  3. 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 { get; private 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 8

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

clip_image035

I hope this post was useful. Thanks for reading  Smile

8 responses to “Walkthrough on Play Background Audio in Windows 7.1 [Mango] Phone”

  1. Sir,
    I have one doubt regarding OS 1.1 development Framework .Sir I am using VS 2010 Ultimate Version.But The Released Version OS7.1 Toolkit for developing (MANGO)apps is for VS 2010 SP1?? Is it so ?

  2. Sir,
    I have one doubt regarding OS 1.1 development Framework .Sir I am using VS 2010 Ultimate Version.But The Released Version OS7.1 Toolkit for developing (MANGO)apps is for VS 2010 SP1?? Is it so ?

  3. […] Walkthrough on Play Background Audio in Windows 7.1 [Mango] Phone (Dhananjay Kumar) […]

  4. […] Debug Mode… In this post, I will walkthrough to “Play Background Audio “in Mango or Window 7.1 […]

  5. […] Walkthrough on Play Background Audio in Windows 7.1 [Mango] Phone […]

  6. Is it support only MP3 format ?

  7. […] used link streaming sound online radio. now want record audio. have no thought how though searched […]

Leave a comment

Create a website or blog at WordPress.com