我正在使用ASP.NET Core和ffmpeg来录制实时视频流。当页面收到get请求时,流应开始记录并使用ffmpeg保存到文件夹。我要这样做,以便在访问stop端点时,ffmpeg进程完全关闭。
不幸的是,离开Get方法后,我无法向stdin发送'q'。使用taskkill需要使用/ F来使ffmpeg进程(不是窗口)强制退出并且无法正确保存视频,从而导致文件损坏。
我尝试使用Process.Kill()
,但也会导致文件损坏。另外,我尝试了Process.CloseMainWindow()
可以正常工作,但仅当进程作为窗口启动时,并且无法在正在使用的服务器中作为窗口启动进程。
我将下面提供的代码包括在内,希望有人可以引导我走上正确的道路。
using System;
...
using Microsoft.Extensions.Logging;
namespace MyApp.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class RecordingController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger<HomeController> _logger;
public RecordingController(ApplicationDbContext context, ILogger<HomeController> logger)
{
_context = context;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult> Get()
{
// Define the os process
var processStartInfo = new ProcessStartInfo()
{
// ffmpeg arguments
Arguments = "-f mjpeg -i \"https://urlofstream.com/video.gci\" -r 5 \"wwwroot/video.mp4\"",
FileName = "ffmpeg.exe",
UseShellExecute = true
};
var p1 = Process.Start(processStartInfo);
// p1.StandardInput.WriteLineAsync("q"); <-- This works here but not in the Stop method
return Ok(p1.Id);
}
// GET: api/Recording/stop
[HttpGet("stop/{pid}")]
public ActionResult Stop(int pid)
{
Process processes = Process.GetProcessById(pid);
processes.StandardInput.WriteLineAsync("q"); // Does not work, is not able to redirect input
return Ok();
}
}
}
我已经找到了解决此问题的方法,希望可以对其他人有所帮助。解决方案是结合使用Singleton和ConcurrentDictionary并将其写入StandardInput。可以写入正在运行的进程的标准输入的唯一方法是,如果您仍然有权访问已启动的Process句柄,并且您将无法从控制器内部对其进行访问,那么您将需要创建一个Singleton并存储进程在ConcurrentDictionary中(非常适合从多个线程进行更新)。
[首先,我创建了一个录音管理器类。 RecordingManager.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MyApp.Services
{
public class RecordingManager
{
// Key int is the ProcessId. Value process is the running Process
private static ConcurrentDictionary<int, Process> _processes = new ConcurrentDictionary<int, Process>();
public Process Start()
{
// Define the os process
var processStartInfo = new ProcessStartInfo()
{
// ffmpeg arguments
Arguments = "-f mjpeg -i https://urlofstream.com/video.gci -r 5 wwwroot/video.mp4",
FileName = "ffmpeg.exe",
RedirectStandardInput = true, // Must be set to true
UseShellExecute = false // Must be set to false
};
Process p = Process.Start(processStartInfo);
// Add the Process to the Dictionary with Key: Process ID and value as the running process
_processes.TryAdd(p1.Id, p);
return p;
}
private Process GetProcessByPid(int pid)
{
return _processes.FirstOrDefault(p => p.Key == pid).Value;
}
public void Stop(int pid)
{
Process p = GetProcessByPid(pid);
// FFMPEG Expects a q written to the STDIN to stop the process
p.StandardInput.WriteLine("q\n");
_processes.TryRemove(pid, out p);
// Free up resources
p.Close()
}
}
}
接下来,我将单例添加到ConfigureServices方法中的startup.cs类中
services.AddSingleton<RecordingManager>();
最后,我将单例添加到控制器构造函数中,并在其中调用方法。 RecordingController.cs
namespace MyApp.Controllers
{
[Route("api/[controller]")]
[Authorize]
public class RecordingController : Controller
{
private readonly ApplicationDbContext _context;
private readonly ILogger<HomeController> _logger;
private readonly RecordingManager _recordingManager;
public RecordingController(ApplicationDbContext context, ILogger<HomeController> logger, RecordingManager recordingManager)
{
_context = context;
_logger = logger;
_recordingManager = recordingManager;
}
[HttpGet]
public async Task<ActionResult> Get()
{
Process p = _recordingManager.Start();
return Ok(p.Id); // Wouldn't recommend simply returning an Ok Result here. Check for issues
}
// GET: api/Recording/stop
[HttpGet("stop/{pid}")]
public ActionResult Stop(int pid)
{
_recordingManager.Stop(pid);
return Ok(); // Wouldn't recommend simply returning an Ok Result here. Check for issues
}
}
}