ffmpeg合並多個視頻


合並多個短視頻為一個視頻,為了保證視頻合並后播放的順序是正確的,所有需要合並的視頻命名是有序的

 /// <summary>
        /// 遍歷文件夾獲取所有視頻路徑
        /// </summary>
        /// <param name="path"></param>
        private void TraverseFolder(string path,string filepath)
        {
            DirectoryInfo dInfo = new DirectoryInfo(path);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Dictionary<int, string> dic2 = new Dictionary<int, string>();
            List<string> list = new List<string>();
            //遍歷該文件夾
            foreach (FileInfo fileitem in dInfo.GetFiles())
            {
                if (fileitem.Extension == ".mp4")
                {
                    dic.Add(fileitem.Name, fileitem.FullName);
                }
            }         
            list = dic2.OrderBy(p => p.Key).Select(p => p.Value).ToList();//遍歷獲取所有需要合並視頻的路徑(為了保證視頻合並后播放的順序是正確的,所有需要合並的視頻命名是有序的)
            VideoCombine(list, filepath); //執行視頻合並操作
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list">需要合並視頻路徑(含文件名和文件類型)集合</param>
        /// <param name="DstFile">合並后文件路徑(含文件名和文件類型)</param>
        public void VideoCombine(List<string> list, string DstFile)
        {
            //DstFile=@"E:\新建文件夾\新視頻.mp4";
            string strTmp = "";
            string strCmd = "";
            StringBuilder sb = new StringBuilder();
            sb.Append("-i \"concat:");
            foreach (var item in list)
            {
                strTmp = item + ".ts";
                strCmd = " -i " + item + " -c copy -bsf:v h264_mp4toannexb -f mpegts " + strTmp + " -y ";
                CombineImplement(strCmd);
                sb.Append($"{strTmp}|");
            }
            sb.Remove(sb.ToString().LastIndexOf('|'), 1);
            sb.Append($"\" -c copy -bsf:a aac_adtstoasc -movflags +faststart {DstFile} -y ");
            var path = sb.ToString();
            CombineImplement(path);
        }
        public void CombineImplement(string strCmd)
        {
            string exe = @"C\ffmpeg.exe";
            //轉換文件類型,由於不是所有類型的視頻文件都支持直接合並,需要先轉換格式
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = exe;//要執行的程序名稱  
            p.StartInfo.Arguments = " " + strCmd;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = false;//可能接受來自調用程序的輸入信息  
            p.StartInfo.RedirectStandardOutput = false;//由調用程序獲取輸出信息   
            p.StartInfo.RedirectStandardError = false;//重定向標准錯誤輸出
            p.StartInfo.CreateNoWindow = false;//不顯示程序窗口   
            p.Start();//啟動程序   
            p.WaitForExit();
            p.Close();
            p.Dispose();
        }

 


免責聲明!

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



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