VLC的C#库:https://github.com/ZeBobo5/Vlc.DotNet
使用VLC播放视频时,有时候视频尺寸与播放的控件大小不一样,导致有黑的边框,如下图所示:
这个问题,在Issue区也有人提出过:https://github.com/ZeBobo5/Vlc.DotNet/issues/652
现解决方案如下:
internal class VLCPlayer
{
const string VLC_LIB_DIRECTORY = @".\VLC";
private VlcMediaPlayer vlcMediaPlayer;
private bool isPlaying = false;//标识是否已经播放,用于没有播放时能够重新播放
public VLCPlayer()
{
string vlcLibPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, VLC_LIB_DIRECTORY);
var options = new string[] { ":avcodec-hw=any", "--rtsp-tcp", "--network-caching=300", };
vlcMediaPlayer = new VlcMediaPlayer(new System.IO.DirectoryInfo(vlcLibPath),options);
vlcMediaPlayer.Playing += VlcMediaPlayer_Playing;
}
private void VlcMediaPlayer_Playing(object sender, VlcMediaPlayerPlayingEventArgs e)
{
isPlaying = true;
SetAspectRatio(vlcMediaPlayer.VideoHostControlHandle);
}
public void Play(string url, IntPtr handle)
{
isPlaying = false;
vlcMediaPlayer.VideoHostControlHandle = handle;
var control = FindControl(handle);
control.SizeChanged -= Control_SizeChanged;
control.SizeChanged += Control_SizeChanged;
vlcMediaPlayer.Play(new Uri(url));
//检测是否在播放,没有播放就重复播放
Task.Factory.StartNew((x) =>
{
Thread.Sleep(3000);
if (isPlaying) return;
string l = x as string;
for (int i = 0; i < 5; i++)
{
if (!isPlaying)
{
vlcMediaPlayer.Play(new Uri(l));
Thread.Sleep(5000);
}
else
{
break;
}
}
},url);
}
private void Control_SizeChanged(object sender, EventArgs e)
{
SetAspectRatio(vlcMediaPlayer.VideoHostControlHandle);
}
/// <summary>
/// 通过句柄找到窗体
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
private System.Windows.Forms.Control FindControl(IntPtr handle)
{
return System.Windows.Forms.Form.FromHandle(handle);
}
/// <summary>
/// 设置视频的宽高比
/// </summary>
/// <param name="handle"></param>
private void SetAspectRatio(IntPtr handle)
{
var control = FindControl(handle);
vlcMediaPlayer.Video.AspectRatio = $"{control.Width}:{control.Height}";
}
public void Pause()
{
vlcMediaPlayer.Pause();
}
public void Stop()
{
vlcMediaPlayer.Stop();
}
}