C# WinForm - RTSP IP摄像头查看器





5.00/5 (1投票)
一个简单的 C# WinForm 应用程序,用于实时播放、抓取快照和录制来自任何 IP 摄像头的 RTSP 流
链接
为了测试目的,你可以使用我的演示 IP 摄像头 RTSP 流
rtsp://stream.szep.cz/user=test_password=test_channel=1_stream=1
引言
RTSP 代表 实时流协议,是一种设计用于在网络上传输多媒体数据的网络协议。它出现在音频/视频传输中,工作在 ISO/OSI 参考模型的应用层,默认端口是 554。实际上,几乎每个 IP 摄像头或 NVR 都支持 RTSP。请记住,有时你需要在摄像头上启用 RTSP,并且具体的 RTSP 地址可能因 IP 摄像头制造商而异。
你可以使用 VLC 库和 VlcControl 在你的 C# WinForm 应用程序中轻松播放 RTSP 流。
该示例项目能够播放、抓取快照、录制并将视频流保存到文件。它还会检查你的计算机上是否安装了 32 位 VLC Media Player - 如果没有,它将引导你下载它。
需要执行的操作
你必须在想要执行此项目的计算机上安装 VLC Media Player。
如果你想在自己的项目中使用的 VLCControl,首先你需要安装 NuGet 包 'VLC.DotNet.Forms'
项目 > 管理 NuGet 包 > 浏览 > 输入 'VLC.DotNet.Forms' > 安装
然后将 VlcControl 添加到你的窗体
工具箱 > VlcControl > 将 VlcControl 拖放到你的窗体中的某个位置
所有 VLC 控制都需要使用位于 VLC 安装文件夹中的 vlclib.dll,在我的例子中是 C:\Program Files (x86)\VideoLAN\VLC。
必须始终在 VlcLibDirectory
属性中设置此路径(你可以在设计器中轻松设置此属性)。在示例项目中,VlcLibDirectory
已经设置好了。
使用代码
现在我们已经在计算机上安装了 32 位 VLC Media Player,安装了 NuGet 包,并将 VlcControl(在我的例子中命名为 VLCPlayer)添加到窗体中。
1. 如何播放 RTSP 流
VLCPlayer.Stop();
VLCPlayer.SetMedia(new Uri("rtsp://something.xx/"), string.Empty);
VLCPlayer.Play();
或者你也可以使用
VLCPlayer.Play(new Uri("rtsp://something.xx/"));
2. 如何播放和录制 RTSP 流,然后将录制内容保存到文件
在定义路径时,你必须使用双反斜杠,否则它将无法工作。
bool IsRecording;
if (!IsRecording)
{
// Start recording
if (VLCPlayer.IsPlaying)
{
string path = $@"c:\\Users\\{Environment.UserName}\\Desktop\\{Guid.NewGuid()}.mp4";
// Magic option string that creates recording:
var mediaOptions = new[] { ":sout=#duplicate{dst=display,dst=std{access=file,mux=mp4,dst=\"" + path + "\"}" };
VLCPlayer.SetMedia(new Uri("rtsp://something.xx/"), mediaOptions);
VLCPlayer.Play();
IsRecording = true;
}
}
else
{
// Stop recording
IsRecording = false;
VLCPlayer.Stop();
// keep playing without recording
VLCPlayer.SetMedia(new Uri("rtsp://something.xx/"), string.Empty);
VLCPlayer.Play();
}
3. 如何拍摄快照,然后保存到文件
在定义路径时,你必须使用双反斜杠,否则它将无法工作。
if (VLCPlayer.IsPlaying)
{
string path = $@"c:\\Users\\{Environment.UserName}\\Desktop\\{Guid.NewGuid()}.png";
VLCPlayer.TakeSnapshot(path);
}
或者,如果你想以像素为单位指定输出图像大小(例如 400x300)
if (VLCPlayer.IsPlaying)
{
string path = $@"c:\\Users\\{Environment.UserName}\\Desktop\\{Guid.NewGuid()}.png";
VLCPlayer.TakeSnapshot(path, 400, 300);
}
4. 如何设置音频音量
VLCPlayer.Audio.Volume = 69;
5. 如何静音音频
VLCPlayer.Audio.IsMute = true;
6. 如何设置自定义纵横比
VLCPlayer.Video.AspectRatio = "16:9"; // 4:3 , 0:0 ...