如何在 c# 中停止 ffmpeg 用户屏幕录制

本文关键字:用户 ffmpeg 屏幕 | 更新日期: 2023-09-27 18:37:14

>我在应用程序中使用 ffmpeg,它可以完美地启动和录制视频,但是当我想停止它时,请按"q",那么我如何将"q"传递给处于运行状态的处理从应用程序。

如何在 c# 中停止 ffmpeg 用户屏幕录制

FFMpeg 正确响应 SIGINT,并应完成视频容器文件的写入。

(如果您需要有关在 C# 中发送信号的信息,请参阅此处)

我相信最新版本的FFMpeg不再使用"q",而是要求ctrl-c退出。

string process = //...process name
Process p = Process.GetProcessesByName(process).FirstOrDefault();
if( p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("q");
}

下面的设置正在为我工作以结束该过程。 在示例中,我在 3 秒后触发,但您可以随时异步将"q"传递给进程。 否则,将记录设置为特定时间量会更有意义。

            string outputFile = "output.mp4";
            if(File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }
            string arguments = "-f dshow -i video='"screen-capture-recorder'" -video_size 1920x1080 -vcodec libx264 -pix_fmt yuv420p -preset ultrafast " + outputFile;
            //run the process
            Process proc = new Process();
            proc.StartInfo.FileName = "ffmpeg.exe";
            proc.StartInfo.Arguments = arguments;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardInput = true;
            proc.ErrorDataReceived += build_ErrorDataReceived;
            proc.OutputDataReceived += build_OutDataReceived;
            proc.EnableRaisingEvents = true;
            proc.Start();
            proc.BeginOutputReadLine();
            proc.BeginErrorReadLine();
            await Task.Delay(3000);
            StreamWriter inputWriter = proc.StandardInput;
            inputWriter.WriteLine("q");
            proc.WaitForExit();
            proc.Close();
            inputWriter.Close();

使用以下代码:

 [System.Runtime.InteropServices.DllImport("User32.dll", EntryPoint = "PostMessageA")]
 private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
 int Key_Q = 81;
 PostMessage(hWnd, 0x100, Key_Q, 0);