进度条显示和拖动控制
视频教程
WPF+LibVLC开发播放器-进度条控制
界面上
界面上线增加一个Slider
控件,当做播放进度条
xml
<Slider
Name="PlaySlider"
Grid.Row="1"
Width="800"
Margin="0,9,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
/>
代码实现
进度条显示进度
在player
上的TimeChanged
中实现实时更新进度条,在Player_TimeChanged
里增加变化,修改Maximum
值为Length
值,修改Slider的Value
为当前的Time
值
csharp
//更新进度条
PlaySlider.Maximum = _player.Length;
PlaySlider.Value = _player.Time;
完整代码:
csharp
public MainWindow()
{
InitializeComponent();
Core.Initialize();
_libVLC = new LibVLC();
_player = new MediaPlayer(_libVLC);
_player.TimeChanged += Player_TimeChanged;
videoView.MediaPlayer = _player;
}
private void Player_TimeChanged(object? sender, MediaPlayerTimeChangedEventArgs e)
{
Dispatcher.Invoke(
new Action(() =>
{
//更新进度条
PlaySlider.Maximum = _player.Length;
PlaySlider.Value = _player.Time;
TimeText.Text =
TimeSpan.FromMilliseconds(_player.Time).ToString(@"hh\:mm\:ss")
+ "/"
+ TimeSpan.FromMilliseconds(_player.Length).ToString(@"hh\:mm\:ss"); //总长
})
);
}
进度条拖动视频进度
接着开发拖动进度条实现更新视频进度的功能
在这里不能使用Slider
的ValueChanged
事件,因为在播放时间更新的时候一直在更新Value值,再拖动就会变成一直闪烁
这里需要用到三个Thumb
的事件
DragStarted
:拖动开始DragDelta
:拖动过程中一直触发DragCompleted
:拖动结束时触发
在控件上增加这三个方法
xml
<Slider
Name="PlaySlider"
Grid.Row="1"
Width="800"
Margin="0,9,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
IsMoveToPointEnabled="True"
Thumb.DragCompleted="PlaySlider_DragCompleted"
Thumb.DragDelta="PlaySlider_DragDelta"
Thumb.DragStarted="PlaySlider_DragStarted" />
这里我们增加一个属性来标记拖动的开始和结束
csharp
bool _isDrag = false;
然后修改时间变化事件,增加判断,让拖动开始时,不再更新,防止拖动异常
csharp
private void Player_TimeChanged(object? sender, MediaPlayerTimeChangedEventArgs e)
{
Dispatcher.Invoke(
new Action(() =>
{
if (!_isDrag)
{
//更新内容
PlaySlider.Maximum = _player.Length;
PlaySlider.Value = _player.Time;
TimeText.Text =
TimeSpan.FromMilliseconds(_player.Time).ToString(@"hh\:mm\:ss")
+ "/"
+ TimeSpan.FromMilliseconds(_player.Length).ToString(@"hh\:mm\:ss"); //总长
}
})
);
}
然后实现拖动的三个方法,
PlaySlider_DragStarted:拖动开始,设置拖动标识为true,然后暂停播放
PlaySlider_DragDelta:拖动过程中,实时更新播放器的进度
PlaySlider_DragCompleted:拖动结束,标识改为false,然后继续播放
csharp
private void PlaySlider_DragStarted(
object sender,
System.Windows.Controls.Primitives.DragStartedEventArgs e
)
{
_isDrag = true;
_player.SetPause(true);
}
private void PlaySlider_DragDelta(
object sender,
System.Windows.Controls.Primitives.DragDeltaEventArgs e
)
{
_player.Time = Convert.ToInt64(PlaySlider.Value);
}
private void PlaySlider_DragCompleted(
object sender,
System.Windows.Controls.Primitives.DragCompletedEventArgs e
)
{
_isDrag = false;
_player.Play();
}
效果
实现进度条跟随播放,拖动更新进度