The BackgroundAudioPlayer
class implements the singleton pattern. The single instance of the BackgroundAudioPlayer
is accessed in your foreground app via its static Instance
property, as shown:
BackgroundAudioPlayer.Instance.Track
= new AudioTrack(
new Uri("http://example.com/Audio.mp3", UriKind.Absolute),
"Track Name", "Artist", "Album", null);
BackgroundAudioPlayer.Instance.Play();
The behavior of the BackgroundAudioPlayer
changes depending on whether it is being used in your foreground app or from an AudioPlayerAgent
. When the BackgroundAudioPlayer
is used in your foreground app, all calls are relayed to your AudioPlayerAgent
. When used from an AudioPlayerAgent
, the BackgroundAudioPlayer
affects the playback of audio directly. Without an AudioPlayerAgent
, the BackgroundAudioPlayer
does nothing.
This dual behavior can be best understood by looking at the internal workings of the BackgroundAudioPlayer
. The BackgroundAudioPlayer
is a proxy that relies on a native implementation of an internal IAudioPlaybackManager
interface. When the BackgroundAudioPlayer
is used in your foreground app, the IAudioPlaybackManager
relays all audio requests to the app’s AudioPlayerAgent
. Conversely, when used from your AudioPlayerAgent
, the IAudioPlaybackManager
uses the native audio playback system instead.
BackgroundAudioPlayer
contains several public methods that allow you to control the playback of audio (see Table 34.1).
BackgroundAudioPlayer
contains several public audio playback-related properties, which are shown in Table 34.2.
BackgroundAudioPlayer
contains a principle event, PlayStateChanged
, which is used to detect, for example, when a track begins playing.
New in Windows Phone 8 is the capability to retrieve the current play state and preceding play state from the PlayStateChangedEventArgs
. For compatibility with Windows Phone 7.1 OS, the signature of the PlayStateChanged
event has not changed in the Windows Phone SDK. Therefore, to retrieve the play states, you must cast the EventArgs
argument to a PlayStateChangedEventArgs
object, as shown in the following example:
void HandlePlayStateChanged(object sender, EventArgs e)
{
/* New in Windows Phone 8, the current and previous playstate
* can be retrieved using the PlayStateChangedEventArgs. */
PlayStateChangedEventArgs args = (PlayStateChangedEventArgs)e;
PlayState currentPlayState = args.CurrentPlayState;
PlayState previousPlayState = args.IntermediatePlayState;
...
}
You see later in the chapter how this event can be used to hide and show UI elements based on the current state of the player.
3.145.46.18