其实不考虑系统兼容性的话有更简单的解决方案:
Media players - Windows apps | Microsoft Docs
如果没办法保证目标机器的系统版本还是建议使用MediaElement。
ProgressBarConvert.cs
internal class ProgressBarConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return TimeSpan.FromMilliseconds((double)value).ToString(@"hh\:mm\:ss\.fff");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((TimeSpan)value).TotalMilliseconds;
}
}
MediaPlayer.xaml
<Slider x:Name="ProgressBar" Style="{DynamicResource PlayerSliderStyle}" Width="1180" Canvas.Top="596" Minimum="0" TickFrequency="30"/>
<TextBlock Text="{Binding ElementName=ProgressBar, Path=Value, Converter={StaticResource ProgressBarConvert}}" FontSize="20"/>
Slider的最大值需要在MediaOpend时获取(媒体文件打开之前获取的不正确);Value通过定时器与视频进度同步;
private DispatcherTimer MediaTimer;
private void VideoPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
ProgressBar.Maximum = VideoPlayer.NaturalDuration.TimeSpan.TotalMilliseconds;
MediaTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(30)
};
MediaTimer.Tick += new EventHandler(Timer_tick);
MediaTimer.Start();
}
private void Timer_tick(object sender, EventArgs e)
{
ProgressBar.Value = VideoPlayer.Position.TotalMilliseconds;
}
显示效果: