Shi*_*mmy 6 .net interaction ffmpeg process processstartinfo
我正在尝试使用ffmepg创建用于媒体文件转换的.NET包装器,这是我尝试过的:
static void Main(string[] args)
{
if (File.Exists("sample.mp3")) File.Delete("sample.mp3");
string result;
using (Process p = new Process())
{
p.StartInfo.FileName = "ffmpeg";
p.StartInfo.Arguments = "-i sample.wma sample.mp3";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
//result is assigned with an empty string!
result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
}
Run Code Online (Sandbox Code Playgroud)
实际发生的是ffmpeg程序的内容打印到Console应用程序,但result变量是一个空字符串.我希望以交互方式控制转换进度,因此用户甚至不必知道我正在使用ffmpeg,但他仍然知道转换进度的详细信息以及应用程序所需的百分比等.
基本上我也很满意只有P/Invoke到转换函数的.NET包装器(我对整个外部库不感兴趣,除非我可以从中提取PI函数).
有ffmpeg和.NET经验的人吗?
更新 请查看我的进一步问题,如何将输入写入正在运行的ffmpeg进程.
这是答案:
static void Main()
{
ExecuteAsync();
Console.WriteLine("Executing Async");
Console.Read();
}
static Process process = null;
static void ExecuteAsync()
{
if (File.Exists("sample.mp3"))
try
{
File.Delete("sample.mp3");
}
catch
{
return;
}
try
{
process = new Process();
ProcessStartInfo info = new ProcessStartInfo("ffmpeg.exe",
"-i sample.wma sample.mp3");
info.CreateNoWindow = false;
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
process.StartInfo = info;
process.EnableRaisingEvents = true;
process.ErrorDataReceived +=
new DataReceivedEventHandler(process_ErrorDataReceived);
process.OutputDataReceived +=
new DataReceivedEventHandler(process_OutputDataReceived);
process.Exited += new EventHandler(process_Exited);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
catch
{
if (process != null) process.Dispose();
}
}
static int lineCount = 0;
static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Input line: {0} ({1:m:s:fff})", lineCount++,
DateTime.Now);
Console.WriteLine(e.Data);
Console.WriteLine();
}
static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output Data Received.");
}
static void process_Exited(object sender, EventArgs e)
{
process.Dispose();
Console.WriteLine("Bye bye!");
}
Run Code Online (Sandbox Code Playgroud)