Encoder/Lib/DetectWorker.cs
2026-01-12 11:32:18 +09:00

61 lines
2.0 KiB
C#

using System.Diagnostics;
namespace Encoder.Lib;
public class DetectWorker
{
private readonly ProcessStartInfo startInfo;
public string? MaxVolume { get; private set; }
public string? MeanVolume { get; private set; }
public DetectWorker(string workingDirectory, string inputFile, string encodeParam)
{
var arguments = $"-y -i \"{inputFile}\" {encodeParam} -f null -";
this.startInfo = new ProcessStartInfo()
{
FileName = "ffmpeg",
WorkingDirectory = workingDirectory,
Arguments = arguments,
};
this.MeanVolume = null;
this.MaxVolume = null;
}
public async ValueTask<int> Run()
{
try
{
Console.WriteLine($"{this.startInfo.FileName} {this.startInfo.Arguments}");
using Process process = new Process();
process.StartInfo = this.startInfo;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
var result = process.Start();
if (!result)
{
throw new FileNotFoundException();
}
var str = await process.StandardError.ReadToEndAsync().ConfigureAwait(false);
await process.WaitForExitAsync().ConfigureAwait(false);
// Console.WriteLine(str);
var maxVolumeLine = str.Split('\n').FirstOrDefault(line => line.Contains("max_volume"));
this.MaxVolume = maxVolumeLine?.Split(':').Skip(1).FirstOrDefault()?.Trim().Replace(" ", "");
var meanVolumeLine = str.Split('\n').FirstOrDefault(line => line.Contains("mean_volume"));
this.MeanVolume = meanVolumeLine?.Split(':').Skip(1).FirstOrDefault()?.Trim().Replace(" ", "");
return process.ExitCode;
}
catch (Exception err)
{
Console.WriteLine(err);
return -1;
}
}
}