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();
        }

猜你喜欢

转载自www.cnblogs.com/macT/p/11771065.html