C#实现视频的批量剪辑功能

篇首,完全没有技术含量的帖子,高手略过,只为十几年后重新捡起的我爱好玩玩。。。

起因,一个朋友说他下载了很多短视频,但只需要要其中的一小截,去头掐尾,在软件里搞来搞去太麻烦,让我帮忙,我这个编程二吊子爽快的接了下来。

还是一二三理清思路,方案就用ffmpeg,命令行剪辑生成新视频,c#做个集成一键处理。。

一,采用预置数据data.txt,记录【视频文件名,起点时间,终止时间】,此为单独一行,多个文件就多行,如下图

二,一个videocut类

class VideoCut
 {
 public string file;
 public string begin;
 public string end;
 public VideoCut(string f,string b,string w)
 {
 file = f;
 begin = b;
 end = w; 
 }
 }

三,解析数据文件data.txt,生成videocut的列表

count = 0;
 listbox.Items.Clear();
 logno("开始解析数据文件....");
 if (!System.IO.File.Exists("data.txt"))
 {
 log("找不到数据文件data.txt");
 return;
 }
 List<VideoCut> list = new List<VideoCut>();
 string[] ary;
 TimeSpan begin;
 TimeSpan end;
 int i = 0;
 foreach (string line in System.IO.File.ReadLines("data.txt"))
 {
 ary = line.Trim().Split(',');
 log("第" + ++i + "行:" + line.Trim());
 if(ary.Length!=3)
 {
 log("数据:"+line.Trim()+",格式不对");
 continue;
 }
 if (!System.IO.File.Exists(ary[0]))
 {
 log("文件:"+ary[0].Trim()+",不存在");
 continue;
 }
 if (!TimeSpan.TryParse(ary[1].Trim(), out begin))
 {
 log("起点时间:" + ary[1].Trim() + ",格式不对");
 continue;
 }
 if (!TimeSpan.TryParse(ary[2].Trim(), out end))
 {
 log("截止时间:" + ary[2].Trim() + ",格式不对");
 continue;
 }
 if (end <= begin)
 {
 log("截止时间应该大于起点时间!!!!!");
 continue;
 }
 list.Add(new VideoCut(ary[0], ary[1], (end-begin).ToString()));
 }
 logno("解析数据文件完毕,成功解析文件:"+list.Count+"个...");
 if (list.Count < 1)
 {
 log("没有数据,退出");
 }

 四,一个ffmpeg的剪辑类

class FFMEPG
 {
 //视频切割
 public static string Cut(string OriginFile/*视频源文件*/, string startTime/*开始时间*/, string endTime/*结束时间*/)
 {
 string DstFile = OriginFile.Replace(".", "a.");
 string strCmd = " -ss "+ startTime
 +" -i " + OriginFile 
 + " -to " +endTime
 + " -vcodec copy -acodec copy " + DstFile + " -y ";
 if (System.IO.File.Exists(DstFile))System.IO.File.Delete(DstFile);
 System.Diagnostics.Process p = new System.Diagnostics.Process();
 p.StartInfo.FileName = "ffmpeg.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();//等待程序执行完退出进程
 
 if (System.IO.File.Exists(DstFile))
 {
 return DstFile;
 }
 return "";
 }
 }

五,循环调用videocut列表

VideoCut c;
 string file;
 for (i = 0; i < list.Count; i++)
 {
 logno("开始剪切第【" +i + "】个文件...");
 c=list[i];
 file = FFMEPG.Cut(c.file, c.begin, c.end);
 if (file.Length > 0)
 {
 log("剪切成功,输出文件:"+file);
 }
 else log("剪切失败.....");
 }
 log("");
 log("");
 log("剪切完成......");

六,大致就这样了,运行如下图

 ffmpeg命令要能够调用哈,放到同目录或都windows系统目录都行。。。

源代码已经上传,可以下载到。。。

作者:xchenbb原文地址:https://blog.csdn.net/xchenbb/article/details/129697765

%s 个评论

要回复文章请先登录注册