本文技術源自外企,並已在多個世界500強大型項目開發中運用。 本文適合有初/中級.NET知識的同學閱讀。(支持.NET/.NET Framework/.NET Core) RabbitMQ作為一款主流的消息隊列工具早已廣受歡迎。相比於其它的MQ工具,RabbitMQ支持的語言更多、功能更完善。 本文 ...
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;