WUYUANS
Just for Sharing

C#重定向ffmpeg输出流

2012年04月12日 分类:学习笔记C#x264

最近用c#做了一个ffmpeg的gui,用来合并、切割视频,其中需要把ffmpeg.exe的输出流显示出来,这就需要重定向ffmpeg的输出流,这个方法也适用x264、mencoder这些编码器的重定向。

c#要调用外部程序有许多方法,我这里选用调用Process的方法,也就是新建一个ffmpeg的进程,具体代码如下。

Process p = new Process();
string ph = Environment.CommandLine;
ph = ph.Substring(0, ph.LastIndexOf('\\') + 1);
if (ph[0] == '"')
    ph = ph.Substring(1);
p.StartInfo.FileName = "\"" + ph + "ffmpeg.exe\"";//ffmpeg与程序在同一文件夹中
p.StartInfo.Arguments = "这里是ffmpeg的一些输入参数";
p.StartInfo.RedirectStandardError = true;//重定向
p.ErrorDataReceived += new DataReceivedEventHandler(SplitOutput);//调用外部处理函数
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;//无窗口
p.Start();
p.BeginErrorReadLine();//开始输出流的读取
p.WaitForExit();//等待,直到处理完毕
p.Close();
p.Dispose();

其中SplitOutput是我定义的一个外部程序,ffmpeg每输出一行信息就会调用这个函数,我们可以在里面让这些信息打印到相应的控件中,这样就完成了输出流的显示。

private void SplitOutput(object sendProcess, DataReceivedEventArgs output)
{
     if (String.IsNullOrEmpty(output.Data)) return;
     this.Invoke(new MethodInvoker(() =>
     {
         textStat.AppendText(output.Data + "\r\n");
               
     }));

}

我这里把输出流输出到了一个TextBox上,由于上面的Process我是用多线程的方式实现的,所以要用Invoke来访问主线程中的TextBox。

这里要注意的是ffmpeg输出流的类型,他并不是我们一般以为的StandardOutput,而是StandardError流,x264也是用的StandardError流,只有mencoder是用标准输出流的。

作者:wuyuan 本文来自Wuyuan's Blog 转载请注明,谢谢! 文章地址: https://www.wuyuans.com/blog/detail/74