在Winform中播放RTSP视频流
在WPF中可以使用LibVLCSharp.WinForms、Emgu.CV组件直接播放RTSP流。
1、LibVLCSharp.WinForms
(1) 引入NuGet包
LibVLCSharp.WinForms。
(2) 准备工作
public VlcVideoControl() { InitializeComponent(); if (!DesignMode) { Core.Initialize(); } _libVlc = new LibVLC(); _mediaPlayer = new MediaPlayer(_libVlc) { Volume = 0, //静音 EnableHardwareDecoding = isMainControl //硬件加速 }; videoViewMain.MediaPlayer = _mediaPlayer; Load += OnLoad; HandleDestroyed += OnHandleDestroyed; } private void OnLoad(object sender, EventArgs e) { DoubleBuffered = true; videoViewMain.Enabled = false; } private void OnHandleDestroyed(object sender, EventArgs args) { _mediaPlayer.Stop(); _mediaPlayer.Dispose(); _libVlc.Dispose(); }
(3) 播放RTSP视频流
var options = new[] { "no-audio", "file-caching=300", "live-capture-caching=300", "disc-caching-caching=300", "network-caching=333", "live-caching=300", _isMainControl || EnableHardwareDecoding ? "avcodec-hw=any" : "" //硬解码 }; using (var media = new Media(_libVlc, new Uri(CameraPara.Url), options)) { _mediaPlayer.Play(media); }
(4) 停止播放
if (_mediaPlayer.IsPlaying) { _mediaPlayer.Stop(); }
2、Emgu.CV
(1) 引入NuGet包
Emgu.CV.UI、Emgu.CV.runtime.windows。
(2) 加载控件
private void EmguVideoControl_Load(object sender, EventArgs e) { DoubleBuffered = true; _imageBox = new ImageBox() { SizeMode = PictureBoxSizeMode.Zoom }; Controls.Add(_imageBox); }
(3) 播放RTSP视频流
public void Play(string url) { _videoCapture = new VideoCapture(url); _videoCapture.ImageGrabbed += OnImageGrabbed; _videoCapture.Start(); } private void OnImageGrabbed(object sender, EventArgs args) { var frame = new Mat(); try { if (_videoCapture.Retrieve(frame) && !frame.IsEmpty) { _imageBox.Image = frame; } } finally { frame.Dispose(); } }
(4) 停止播放
public void Stop() { if (_videoCapture != null) { _videoCapture.ImageGrabbed -= OnImageGrabbed; _videoCapture.Dispose(); _videoCapture = null; } }