软件界面:
测试环境:
VS2019
.NET Framework 4.7.2
OpencvSharp4.8.0
输入RTSP流地址即可拉取RTSP流,支持抓拍和录制RTSP流视频,且支持支持按固定时间保存,比如我想5分钟保存一个视频,设置保存间隔为300,代码已经封装成类模块,调用十分简单?,代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FIRC;
using OpenCvSharp;
namespace RtspDemo
{
public partial class Form1 : Form
{
RtspManager rm = new RtspManager();
bool startRecordVideo = false;
int totalSaveFrameCount = 0;
VideoManager vm = null;
int startIndex = 0;
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void btn_connect_Click(object sender, EventArgs e)
{
if(btn_connect.Text=="连接")
{
if (string.IsNullOrEmpty(tb_rtsp.Text))
{
tssl_show.Text = "rtsp流地址错误!";
return;
}
rm.Connect(tb_rtsp.Text);
if (rm.Connected)
{
tssl_show.Text = "连接成功";
btn_connect.Text = "停止";
rm.Start();
}
else
{
tssl_show.Text = "连接失败";
}
}
else
{
rm.Stop();
rm.DisConnect();
btn_connect.Text = "连接";
tssl_show.Text = "连接中断!";
}
}
private void Form1_Load(object sender, EventArgs e)
{
rm.GetImage += Rm_GetImage;
rm.GetStatus += Rm_GetStatus;
}
private void Rm_GetStatus(string msg)
{
if(msg=="disconnect")
{
btn_connect.Text = "连接";
btn_video.Text = "开始录像";
vm.Dispose();
}
}
private void Rm_GetImage(OpenCvSharp.Mat frame)
{
if(startRecordVideo)
{
startIndex++;
if(startIndex>=totalSaveFrameCount)
{
startIndex = 0;
var saveFile = GetTimeString() + ".mp4";
vm = new VideoManager(saveFile, FourCC.MP4V, rm.Fps, rm.Width, rm.Height);
}
vm.WriteFrame(frame);
}
pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(frame);
}
public string GetTimeString()
{
return DateTime.Now.ToString("yyyyMMdd-HHmmss_fff");
}
private void btn_pic_Click(object sender, EventArgs e)
{
if(pictureBox1.Image!=null)
{
var saveFile = GetTimeString() + ".jpg";
pictureBox1.Image.Save(saveFile,ImageFormat.Jpeg);
tssl_show.Text = "抓拍成功,保存为" + saveFile;
}
}
private void btn_video_Click(object sender, EventArgs e)
{
if(btn_video.Text=="开始录像")
{
if(btn_connect.Text=="连接")
{
tssl_show.Text = "请先连接RTSP流!";
return;
}
btn_video.Text = "停止录像";
btn_video.Update();
Task.Run(() => {
totalSaveFrameCount = Convert.ToInt32(tb_interval.Text) * rm.Fps;
startIndex = 0;
var saveFile = GetTimeString() + ".mp4";
vm = new VideoManager(saveFile,FourCC.MP4V,rm.Fps,rm.Width,rm.Height);
startRecordVideo = true;
});
}
else
{
vm.Dispose();
startRecordVideo = false;
btn_video.Text ="开始录像";
}
}
}
}
视频演示:
源码下载地址: