C#中使用ffmpeg合並視頻


首先將最新的ffmpeg.exe放到debug路徑下,下載地址 http://www.ffmpeg.org/download.html

然后調用此方法

  public void CombineMp4WithoutTxt(string StrMP4A, string StrMP4B, string StrOutMp4Path)
        {
            Process p = new Process();//建立外部調用線程
            p.StartInfo.FileName = System.Windows.Forms.Application.StartupPath + "\\ffmpeg.exe";//要調用外部程序的絕對路徑
            string StrArg = "-i concat:\"" + StrMP4A + "|" + StrMP4B + "\" -vcodec copy -acodec copy " + StrOutMp4Path + " -y";
            p.StartInfo.Arguments = StrArg;

            p.StartInfo.UseShellExecute = false;//不使用操作系統外殼程序啟動線程(一定為FALSE,詳細的請看MSDN)
            p.StartInfo.RedirectStandardError = true;//把外部程序錯誤輸出寫到StandardError流中(這個一定要注意,FFMPEG的所有輸出信息,都為錯誤輸出流,用StandardOutput是捕獲不到任何消息的...這是我耗費了2個多月得出來的經驗...mencoder就是用standardOutput來捕獲的)
            p.StartInfo.CreateNoWindow = true;//不創建進程窗口
            p.ErrorDataReceived += new DataReceivedEventHandler(Output);//外部程序(這里是FFMPEG)輸出流時候產生的事件,這里是把流的處理過程轉移到下面的方法中,詳細請查閱MSDN
            p.Start();//啟動線程
            p.BeginErrorReadLine();//開始異步讀取
            p.WaitForExit();//阻塞等待進程結束
            p.Close();//關閉進程
            p.Dispose();//釋放資源
        }

此段代碼是異常拋出處理,請自行添加代碼

   private void Output(object sendProcess, DataReceivedEventArgs output)
        {
            if (!String.IsNullOrEmpty(output.Data))
            {
                //處理方法...
            }
        }

其中:

StrMP4A代表前視頻物理路徑如D:\A.mp4,StrMP4B代表后視頻物理路徑如D:\B.mp4,StrOutMp4Path代表合成的視頻物理路徑如D:\AB.mp4。

如果合成的效果不理想,如只合並了前視頻,或者合並后只有聲音都情況,請按照fmpeg.exe的CMD指令進行測試(請自行百度需要的命令),測試完畢修改此行即可

   string StrArg = "-i concat:\"" + StrMP4A + "|" + StrMP4B + "\" -vcodec copy -acodec copy " + StrOutMp4Path + " -y"; 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM