VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • ffmpeg视频格式转换h264 C#调用exe

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:\ffmpeg\bin\ffmpeg.exe";
string originalVideoFile = @"E:\local\video.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;
复制代码

 

 


相关教程