详解C#如何实现分割视频

在前面两篇写完了对于GIF动态图片的分割和合成,这一篇来写下将视频文件分割成一帧帧图片的方法。

详解C#如何实现分割视频

开发环境

.NET Framework版本:4.5

开发工具

Visual Studio 2013

实现代码

public static void Run(string cmd)
{
try
{
string ffmpeg = AppDomain.CurrentDomain.BaseDirectory + "ffmpeg.exe";
ProcessStartInfo startInfo = new ProcessStartInfo(ffmpeg);
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = cmd;
Process process = Process.Start(startInfo);
process.WaitForExit(5000);
process.Kill();
}
catch { }
}

/// <summary>
/// 分割视频
/// </summary>
/// <param name="videoPath">视频路径</param>
/// <param name="outPath">输出图片路径</param>
public static void Split(string videoPath, string outPath)
{
Run(string.Format(" -i {0}  -r 10 -y -f image2 -ss 00:00:01 {1}\\%d.jpg", videoPath, outPath));
}

/// <summary>
/// 按时间获取某帧图片
/// </summary>
/// <param name="videoPath">视频路径</param>
/// <param name="outPath">输出图片路径</param>
/// <param name="frameTime">时间(格式:00:00:01)</param>
public static void GetFrame(string videoPath, string outPath, string frameTime)
{
Run(string.Format("-ss 00:00:01 -i {1} {2}", frameTime, videoPath, outPath));
}
private void btn_select_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "视频|*.mp4;*.avi";
ofd.Title = "请选择视频文件";
ofd.InitialDirectory = Application.StartupPath;
if (ofd.ShowDialog() == DialogResult.OK)
{
axWindowsMediaPlayer1.URL = ofd.FileName;
string outPath = Application.StartupPath + "\\cover.jpg";
FFmpegUtil.GetFrame(ofd.FileName, outPath, "00:00:01");
pictureBox1.Image = Image.FromFile(outPath);
}
}

private void btn_split_Click(object sender, EventArgs e)
{
if(!File.Exists(axWindowsMediaPlayer1.URL)){
MessageBox.Show("未选择视频");
return;
}
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "选择存储位置";
fbd.ShowNewFolderButton = true;
   if (fbd.ShowDialog() == DialogResult.OK)
{
string[] files = Directory.GetFiles(fbd.SelectedPath);
foreach (string file in files)
{
File.Delete(file);
}
FFmpegUtil.Split(axWindowsMediaPlayer1.URL, fbd.SelectedPath);
if (MessageBox.Show("视频分割完成,是否打开文件夹?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Process.Start(fbd.SelectedPath);
}
}

}

实现效果

详解C#如何实现分割视频

代码解析:视频分割技术主要是利用了FFMpeg来实现的,C#在这里其实只是一个调用者。这个在方法Run中可以看的出来,首先是需要将FFMpeg放到debug目录下的,然后使用Process类来调用;这里有个问题需要注意下,就是调用后经常会被卡住,没办法退出来,所以使用了WaitForExit(2000)来处理。并且在等待结束后将该进程给Kill掉了,这个方式可能不太规范,如有更好的方法,感谢指教。

调用的话就直接输入命令就可以了,代码中分别使用了以下两条命令:

  • 获取第一秒的图片作为封面图显示到了图片控件中
  • 将视频分割成一张张图片并保存到了文件夹中