I’m currently developing a WPF application which requires strictly timing, says, being late 2 seconds matters.
I have a MediaElement mediaPlayer which seeks to a new position and play every time a Dispatcher timer is fired. But I notice that the mediaPlayer.Position is not very synced with the timer. In the example below, I set the dispatcherTimer fired after 55 seconds, but the value received from MessageBox in timer_Tick is 108.276746, which is late 2 seconds (55 + 55 = 110).
private void button1_Click(object sender, RoutedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(55);
timer.Tick += new EventHandler(timer_Tick);
mediaPlayer.Source = new Uri("test.wma", UriKind.Relative);
_currentPosition = 55;
mediaPlayer.Position = TimeSpan.FromSeconds(_currentPosition);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Position" + mediaPlayer.Position.TotalSeconds);// print around 108 seconds
}
This is the problem because I need the mediaPlayer position is perfectly synced with the dispatcher timer.
For more information, the root problem here is: the dispatcher timer to strictly follow the mediaElement progress, because I need to sync other controls with the position that mediaPlayer. Being late 2 seconds is unacceptable. Does anyone know how to achieve this effect?
UPDATE PURPOSE: I’m trying to “switch illustration image” according to the playing position from an audio. For example, when the narrator read to “… We have a beautiful house” in the audio, the program will show pictures of a beautiful building. But now since the position is late, it will show the picture long before the audio mentions it.
As pointed out, it takes time for the media elements to load, therefore it is not wise to use a countdown timer. You should do the the other way round: the DispatchTimer fires say like 1 or 2 times every second, and when it’s fired you check the position of the media element. If it’s at a certain position then show the picture.
This approach also limits the maximum error do the time interval of your DispatchTimer events, assuming that the system fires them accurately.