i'm building a music player in WPF, i'm going to add a trackbar for the current playing track, and i'm going to use a dispatcher timer to add a running duration on the left side of the trackbar
0:45 ----------|---------------------------- 3:13
i want the time on the left to change depending on wether user drags left or right in to the trackbar.
check iTunes.
can anyone help me? thanks!
Assuming that you are using a MediaPlayer
element, you can use the MediaPlayer.Position
property to notify you of its current playing position. You will need to use a DispatcherTimer
to keep updating the property that is data bound to the UI element displaying the current playing position. To make this work, you'll also need to set the Slider.Maximum
property to the correct value. Here is a basic example:
In code behind:
private void InitialiseMediaPlayer()
{
mediaPlayer = new MediaPlayer();
mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
mediaPlayer.Open(new Uri(SomeFilePath, UriKind.Absolute));
}
private void MediaPlayer_MediaOpened(object sender, EventArgs e)
{
if (mediaPlayer.NaturalDuration.HasTimeSpan)
{
SliderMaximum = mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
mediaPlayerTimer = new DispatcherTimer();
mediaPlayerTimer.Interval = TimeSpan.FromMilliseconds(1000);
mediaPlayerTimer.Tick += MediaPlayerTimer_Tick;
mediaPlayerTimer.Start();
mediaPlayer.Play();
}
}
private void MediaPlayerTimer_Tick(object sender, EventArgs e)
{
Position = mediaPlayer.Position.TotalSeconds;
Time = mediaPlayer.Position;
}
In XAML:
<Slider Grid.Column="1" Value="{Binding Position, FallbackValue=0}" Maximum="{Binding
SliderMaximum, FallbackValue=0, Mode=OneWay}" Minimum="0" Margin="5,0"
VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Text="{Binding Time, StringFormat={}{0:hh}:{0:mm}:{0:ss},
FallbackValue=00:00:00, Mode=OneWay}" VerticalAlignment="Center" />
You may also need to add the following line into the Position
property setter:
mediaPlayer.Position = TimeSpan.FromSeconds(position);