- 在C#中使用FFmpeg通过Process启动ffmpeg.exe,使用命令行的方式,进行功能的开发。本案例实现了拉流、推流、录制的功能。可以应用于各种具备RTSP流的监控及摄像机的功能开发。
- 觉得有用的朋友可以点赞加关注,谢谢。
-
下载FFmpeg
下载后,将ffmpeg.exe放入项目目录中,我个人把放ffmpeg.exe、ffplay.exe、ffprobe.exe三大工具都放进去了,也可按需。 具体三大工具的学习请自行查文档FFmpeg文档
-
拉流推流
private void btnPush_Click(object sender, RoutedEventArgs e)
{
string path = Directory.GetCurrentDirectory() + "\\FFmpeg";
Process FFMPEG = new Process();
FFMPEG.StartInfo.FileName = "cmd.exe";
FFMPEG.StartInfo.CreateNoWindow = true;//在已存在控制台时,此参数无效
FFMPEG.StartInfo.UseShellExecute = false;
FFMPEG.StartInfo.RedirectStandardInput = true;
FFMPEG.StartInfo.RedirectStandardOutput = true;
FFMPEG.StartInfo.WorkingDirectory = path;
if (FFMPEG.Start())
{
//此为网络摄像头
if (cmbSource.SelectedIndex == 0)
{
FFMPEG.StandardInput.WriteLine($"ffmpeg -thread_queue_size 1000 -r 30 -i {txbUrl.Text} -vcodec libx264 -acodec copy -preset:v ultrafast -tune:v zerolatency -max_delay 10 -g 50 -sc_threshold 0 -f flv {txbPushUrl.Text}");
FFMPEG.StandardInput.Flush();
}
//此为屏幕推流
if (cmbSource.SelectedIndex == 1)
{
FFMPEG.StandardInput.WriteLine($"ffmpeg -thread_queue_size 1000 -r 30 -f gdigrab -i desktop -vcodec libx264 -acodec copy -preset:v ultrafast -tune:v zerolatency -max_delay 10 -g 50 -sc_threshold 0 -f flv {txbPushUrl.Text}");
FFMPEG.StandardInput.Flush();
}
//此为USB摄像头
if (cmbSource.SelectedIndex == 2)
{
FFMPEG.StandardInput.WriteLine($"ffmpeg -thread_queue_size 1000 -r 30 -f dshow -i video='Cam' -vcodec libx264 -acodec copy -preset:v ultrafast -tune:v zerolatency -max_delay 10 -g 50 -sc_threshold 0 -f flv {txbPushUrl.Text}");//video=摄像头名称
FFMPEG.StandardInput.Flush();
}
}
}
3.录屏
Process FFMPEG = new Process();
private void StartRecord()
{
string path = Directory.GetCurrentDirectory() + "\\FFmpeg\\ffmpeg.exe";
string myVideos = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
string cmd = $"-rtsp_transport tcp -i {RTSPUrl} -c copy -f mp4 {myVideos + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".mp4"} -y";
FFMPEG.StartInfo.FileName = path;
FFMPEG.StartInfo.Arguments = cmd;
FFMPEG.StartInfo.CreateNoWindow = true;
FFMPEG.StartInfo.UseShellExecute = false;
FFMPEG.StartInfo.RedirectStandardInput = true;
//FFMPEG.StartInfo.RedirectStandardOutput = true;
FFMPEG.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "\\FFmpeg";
if (FFMPEG.Start())
{
IsRecording = true;
imgSave.Source = new BitmapImage(new Uri("pack://application:,,,/UI/savered.png"));
btnSave.ToolTip = "录制中...";
}
}
private void StopRecord()
{
FFMPEG.StandardInput.WriteLine("q");
FFMPEG.WaitForExit();
FFMPEG.Close();
IsRecording = false;
imgSave.Source = new BitmapImage(new Uri("pack://application:,,,/UI/save.png"));
btnSave.ToolTip = "录制";
}