使用LibVLCSharp.WPF实现视频播放、停止、暂停功能
1, NuGet 添加 VideoLAN.LibVLC.Windows
2. NuGet 添加 LibVLCSharp.WPF
3. wpf 代码如下:
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="40" />
<!-- <RowDefinition Height="40" /> -->
</Grid.RowDefinitions>
<wpf:VideoView Name="VlcControl" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Button Content="播放" Click="Play_OnClick"></Button>
<Button Content="停止" Click="Stop_OnClick" Width="80"></Button>
<Button Content="暂停" Click="Pause_OnClick" Width="80"></Button>
</StackPanel>
</Grid>
4. .cs代码如下:
public partial class MainWindow : Window
{
private LibVLC _libVLC;
private MediaPlayer _mediaPlayer;
public MainWindow()
{
InitializeComponent();
Core.Initialize();// 初始化 LibVLC
_libVLC = new LibVLC();
_mediaPlayer = new MediaPlayer(_libVLC);
VlcControl.MediaPlayer = _mediaPlayer;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
//取整设置成刚好的网格大小
}
private void PlayOrPauseButton_Checked(object sender, RoutedEventArgs e)
{
this.Play();
}
private void PlayOrPauseButton_Unchecked(object sender, RoutedEventArgs e)
{
}
private void Play()
{
//调用Play()时,MediaElement会将其Position设置为0
if (_mediaPlayer.State == VLCState.Paused)
{
var oldTime = _mediaPlayer.Time;
_mediaPlayer.Play();
_mediaPlayer.Time = oldTime;
}
else
{
string filePath = @"E:\1.avi";
_mediaPlayer.Play(new Media(_libVLC, new Uri(filePath, UriKind.RelativeOrAbsolute)));
}
}
private void Stop_OnClick(object sender, RoutedEventArgs e)
{
_mediaPlayer.Stop();
}
private void Pause_OnClick(object sender, RoutedEventArgs e)
{
_mediaPlayer.Pause();
}
private void Play_OnClick(object sender, RoutedEventArgs e)
{
Play();
}
}