在现在的项目中需要使用到播放视频的功能,本来打算使用VLC来做的。后来发现WPF 4.0之后新增了MediaElement类,可以实现视频播放。
<Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid Background="Black"> <MediaElement x:Name="MediaPlayer" LoadedBehavior="Manual" MediaOpened="MediaPlayer_MediaOpened" /> </Grid> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <StackPanel Grid.Column="1" Orientation="Horizontal"> <Button x:Name="ButtonOpen" Click="ButtonOpen_Click" Content="Open..." Width="100" Height="25" Margin="5"/> <Button x:Name="ButtonPlay" Click="ButtonPlay_Click" Content="Play" Width="100" Height="25" Margin="5" /> <Button x:Name="ButtonStop" Click="ButtonStop_Click" Content="Stop" Width="100" Height="25" Margin="5" /> <Button x:Name="ButtonForward" Click="ButtonForward_Click" Content="Forward" Width="100" Height="25" Margin="5" /> <Button x:Name="ButtonBack" Click="ButtonBack_Click" Content="Back" Width="100" Height="25" Margin="5" /> </StackPanel> </Grid> </Grid>
private string _videoPath; public MainWindow() { InitializeComponent(); } private void ButtonOpen_Click(object sender, RoutedEventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Video File(*.avi;*.mp4;*.mkv;*.wav;*.rmvb)|*.avi;*.mp4;*.mkv;*.wav;*.rmvb|All File(*.*)|*.*"; if(dialog.ShowDialog().GetValueOrDefault()) { _videoPath = dialog.FileName; } } private void ButtonPlay_Click(object sender, RoutedEventArgs e) { MediaPlayer.Source = new Uri(_videoPath); MediaPlayer.Play(); } private void ButtonStop_Click(object sender, RoutedEventArgs e) { MediaPlayer.Stop(); } private void ButtonForward_Click(object sender, RoutedEventArgs e) { MediaPlayer.Position = MediaPlayer.Position + TimeSpan.FromSeconds(20); } private void ButtonBack_Click(object sender, RoutedEventArgs e) { MediaPlayer.Position = MediaPlayer.Position - TimeSpan.FromSeconds(20); } private void MediaPlayer_MediaOpened(object sender, RoutedEventArgs e) { // Get the lenght of the video int duration = MediaPlayer.NaturalDuration.TimeSpan.Seconds; }
这样就可以简单的实现对视频的播放,暂停,快进,快退等。不过MediaElement是有缺陷的,它支持的视频格式和Windows Media Player一样。可以把MediaElement看成是WMP的一个WPF组件。如果要播放WMP不支持的格式。
1. 使用VLC开源库,支持的视频格式非常多,地址:https://github.com/videolan/vlc
2. 在本地安装解码器组件,类似的有:K-Lite Codec Pack。
这样就可以实现一个WPF版本的"万能播放器"。
感谢您的阅读,代码点击这里下载。