Monitoring Playback Progress
The viewmodel contains a Position
property that reflects the progress of the current AudioTrack
. Because the BackgroundAudioPlayer
does not have facility to monitor the progress of a track directly, the viewmodel uses a Timer
to periodically raise a property changed event for the Position
property. The tick handler is shown in the following excerpt:
void HandleTimerTick(object state)
{
if (player.PlayerState == PlayState.Playing)
{
OnPropertyChanged(() => Position);
}
}
When a Position
property change is detected in the view, it prompts a Slider
control to reread the property. The Position
get accessor calculates the position value, which is returned as a value between 0 and 1, as shown:
public double Position
{
get
{
if (player.Track == null || player.Track.Duration.TotalSeconds < 1)
{
return 0;
}
double result = player.Position.TotalSeconds
/ player.Track.Duration.TotalSeconds;
return result;
}
set
{
if (player.Track != null)
{
double newSeconds = player.Track.Duration.TotalSeconds * value;
TimeSpan newPosition = TimeSpan.FromSeconds(newSeconds);
player.Position = newPosition;
}
OnPropertyChanged(() => Position);
}
}
Raising a property changed event for the Position
property causes the Slider
, which is bound to the property, to be updated. The Slider
is defined like so:
<Slider Value="{Binding Position, Mode=TwoWay}" Minimum="0" Maximum="1" />
Figure 3 shows the MainPage
with the slider indicating the progress of the current track and the application bar icon buttons for controlling playback.
FIGURE 3 A user interface to control the BackgroundAudioPlayer
from a foreground app.
Numerous possibilities exist for
extending an app such as this. For example, it could be extended to
include a view for the playlist or an image for the album art—the sky’s
the limit!