XiangTan_DM/DM_Weight/util/FFmpegHelper.cs

80 lines
3.1 KiB
C#
Raw Normal View History

2025-07-21 15:24:38 +08:00

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace DM_Weight.util
{
public class FFmpegHelper
{
private Process _ffmpegProcess;
private string _ffmpegPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ffmpeg.exe");
//是否停止录屏标志
public bool stopFlag = false;
public void StartRecording(string outputPath, int frameRate = 30)
{
//int width = (int)SystemParameters.PrimaryScreenWidth;
//int height =(int)SystemParameters.PrimaryScreenHeight;
int segmentDuration = 1800; // 每段半小时
string args = $"-f gdigrab -framerate {frameRate} " +
$"-i desktop -preset ultrafast -t {segmentDuration} {outputPath}";
_ffmpegProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = _ffmpegPath,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardInput = true
}
};
_ffmpegProcess.Start();
ThreadPool.QueueUserWorkItem(CheckFFmpegProcess); // 检查FFmpeg进程是否完成以开始下一个录制段
}
public void StopRecording()
{
_ffmpegProcess?.StandardInput.WriteLine("q");
_ffmpegProcess?.WaitForExit(1000);
_ffmpegProcess?.Close();
stopFlag = true;
}
private void CheckFFmpegProcess(object state)
{
try
{
if (!stopFlag)
{
_ffmpegProcess.WaitForExit(); // 等待FFmpeg进程结束
if (!_ffmpegProcess.HasExited) return; // 如果进程未结束,则不继续
// 开始下一个录制段,如果需要循环录制,可以取消注释下面的代码行并适当调整逻辑
// StartRecording(); // 注意:这将无限循环录制,可能需要用户界面干预来停止或重置计数器。
string _outputFolder;
string _outputFilePath;
_outputFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Log", "ScreenRecordings");
if (!Directory.Exists(_outputFolder))
{
Directory.CreateDirectory(_outputFolder);
}
// 生成输出文件名
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
_outputFilePath = Path.Combine(_outputFolder, $"{timestamp}.webm");
StartRecording(_outputFilePath, 25);
}
}
catch (Exception)
{
}
}
}
}