ffmpeg视频格式转换h264 C#调用exe

  • ffmpeg视频格式转换h264 C#调用exe已关闭评论
  • 199 次浏览
  • A+
所属分类:.NET技术
摘要

FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

官网:http://ffmpeg.org/

本文介绍Windows环境C# 调用ffmpeg.exe 来转换视频

public class ProcessUtil     {         private bool outPut;          public string ProcessOutPut = "";          public ProcessUtil(bool outPut = false)         {             this.outPut = outPut;         }         private void Output(object sendProcess, DataReceivedEventArgs output)         {             ProcessOutPut += output.Data;             Process p = sendProcess as Process;             if (p.HasExited && p.ExitCode == 1)             {                 // throw new Exception("视频处理失败");             }         }          public bool RunExe(string exePath, string argStr)         #region         {             //ProcessOutPut = "";             bool isok = false;             Process p = new Process();//建立外部调用线程             p.StartInfo.FileName = exePath;             p.StartInfo.Arguments = argStr; //参数(这里就是FFMPEG的参数了)              p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序启动线程(一定为FALSE,详细的请看MSDN)             p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,FFMPEG的所有输出信息,都为错误输出流,用StandardOutput是捕获不到任何消息的             p.StartInfo.CreateNoWindow = false;//不创建进程窗口             try             {                 if (this.outPut)                 {                     p.StartInfo.StandardErrorEncoding = Encoding.UTF8;                     p.ErrorDataReceived += new DataReceivedEventHandler(Output);//外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN                 }                 p.Start();//启动线程                 p.BeginErrorReadLine();//开始异步读取                 p.WaitForExit();//阻塞等待进程结束                                 //ProcessOutPut = this.ProcessOutPut;             }             catch (Exception exp)             {                 //Console.WriteLine(exp.Message);                 return isok;             }             finally             {                 if (p.HasExited && p.ExitCode == 1) // 发生错误                     isok = false;                 else                     isok = true;                 p.Close();                 p.Dispose();             }             return isok;         }         #endregion     }

 

调用代码:

string processPath = @"E:ffmpegbinffmpeg.exe"; string originalVideoFile = @"E:localvideo.mp4"; string targetFile = $@"E:local名称{Guid.NewGuid().ToString("N")}.mp4";  //ffmpeg -i input_file -vcodec h264 output_file  //直接转换为h264格式  string argStr = $"-y -i {originalVideoFile} -s 720X480 -b:v 1800k -r 30 -f mp4 " + targetFile; //参数(这里就是FFMPEG的参数了) ";  string output = ""; var p = new FFexe.ProcessUtil(true); bool re = p.RunExe(processPath, argStr); output = p.ProcessOutPut;