FFmpeg是一个有点难以解析的工具,但无论如何,以下是您需要知道的内容。
首先,FFmpeg不支持RedirectOutput选项
您需要做的是,不直接启动ffmpeg,而是启动cmd.exe
,将ffmpeg作为参数传入,并通过命令行输出将输出重定向到“监视文件”中...请注意,在while (!proc.HasExited)
循环中,您可以读取此文件以获取实时FFmpeg状态,或者如果这是一个快速操作,则只需在最后读取它即可。
FileInfo monitorFile = new FileInfo(Path.Combine(ffMpegExe.Directory.FullName, "FFMpegMonitor_" + Guid.NewGuid().ToString() + ".txt"));
string ffmpegpath = Environment.SystemDirectory + "\\cmd.exe";
string ffmpegargs = "/C " + ffMpegExe.FullName + " " + encodeArgs + " 2>" + monitorFile.FullName;
string fullTestCmd = ffmpegpath + " " + ffmpegargs;
ProcessStartInfo psi = new ProcessStartInfo(ffmpegpath, ffmpegargs);
psi.WorkingDirectory = ffMpegExe.Directory.FullName;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.Verb = "runas";
var proc = Process.Start(psi);
while (!proc.HasExited)
{
System.Threading.Thread.Sleep(1000);
}
string encodeLog = System.IO.File.ReadAllText(monitorFile.FullName);
很好,现在你已经获得了FFmpeg输出的日志。接下来是获取持续时间。持续时间行看起来像这样:
Duration: 00:10:53.79, start: 0.000000, bitrate: 9963 kb/s
将结果清理成一个List<string>
:
var encodingLines = encodeLog.Split(System.Environment.NewLine[0]).Where(line => string.IsNullOrWhiteSpace(line) == false && string.IsNullOrEmpty(line.Trim()) == false).Select(s => s.Trim()).ToList();
...然后循环遍历它们,寻找Duration
。
foreach (var line in encodingLines)
{
if (line.StartsWith("Duration"))
{
var duration = ParseDurationLine(line);
}
}
以下是一些可以帮助您解析的代码:
private TimeSpan ParseDurationLine(string line)
{
var itemsOfData = line.Split(" "[0], "="[0]).Where(s => string.IsNullOrEmpty(s) == false).Select(s => s.Trim().Replace("=", string.Empty).Replace(",", string.Empty)).ToList();
string duration = GetValueFromItemData(itemsOfData, "Duration:");
return TimeSpan.Parse(duration);
}
private string GetValueFromItemData(List<string> items, string targetKey)
{
var key = items.FirstOrDefault(i => i.ToUpper() == targetKey.ToUpper());
if (key == null) { return null; }
var idx = items.IndexOf(key);
var valueIdx = idx + 1;
if (valueIdx >= items.Count)
{
return null;
}
return items[valueIdx];
}