在.net中运用ffmpeg 操作视频

1 篇文章 0 订阅

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.IO;

using System.Text;

namespace learun.util

{

/// <summary>

/// ffmpeg视频相关处理的类

/// </summary>

public class FFmpegUtil

{

public static int Run(string cmd)

{

try

{

//string ffmpeg = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"FFmpeg\ffmpeg.exe";

string ffmpeg = ConfigHelper.GetConfig().MultimediaFile.Replace("/", "\\") + @"FFmpeg\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(3000);

process.Kill();

return 1;

}

catch (Exception ex)

{

return -1;

}

}

public static int Run1(string cmd)

{

int r = 0;

try

{

//string ffmpeg = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"FFmpeg\ffmpeg.exe";

string ffmpeg = ConfigHelper.GetConfig().MultimediaFile.Replace("/", "\\") + @"FFmpeg\ffmpeg.exe";

Process p = new Process();

p.StartInfo.FileName = ffmpeg;

p.StartInfo.Arguments = cmd;

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.CreateNoWindow = true;

string a = string.Empty;

p.ErrorDataReceived += new DataReceivedEventHandler((s, message) =>

{

//Response.Write(message.Data);

a = message.Data;

});//外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN

p.Start();//启动线程

p.BeginErrorReadLine();//开始异步读取

p.WaitForExit();//阻塞等待进程结束

p.Close();//关闭进程

p.Dispose();//释放资源

r = 1;

}

catch (Exception ex)

{

r = -1;

}

return r;

}

/// <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));

}

/ <summary>

/ 批量添加图片水印

/ </summary>

/ <param name="videoPath"></param>

/ <param name="outPath"></param>

/ <param name="listImg"></param>

//public static void AddListImageMark(string videoPath, string outPath, List<ImgMark> listImg)

//{

// string imgs = "", postions = "";

// foreach (ImgMark mark in listImg)

// {

// imgs += " -i " + mark.ImgPath;

// postions += "overlay=" + mark.Postion.X + ":" + mark.Postion.Y + ",";

// }

// postions = postions.Remove(postions.Length - 1);

// Run(string.Format("-i {0}{1} -filter_complex \"{2}\" {3}", videoPath, imgs, postions, outPath));

//}

/ <summary>

/ 批量添加图片水印

/ </summary>

/ <param name="videoPath"></param>

/ <param name="outPath"></param>

/ <param name="listImg"></param>

//public static void AddImageMark(string videoPath, string outPath, ImgMark img)

//{

// Run(string.Format("-i {0} -i {1} -filter_complex overlay {2}", videoPath, img.ImgPath, outPath));

// //./ ffmpeg -i input.mp4 -i iQIYI_logo.png - filter_complex overlay output.mp4

//}

/ <summary>

/ 添加文字水印

/ </summary>

/ <param name="videoPath">视频路径</param>

/ <param name="outPath">输出路径</param>

/ <param name="textMark">水印属性</param>

//public static void AddTextMark(string videoPath, string outPath, TextMark textMark)

//{

// Run(string.Format(" -i {0} -vf \"drawtext=fontfile={1}: text='{2}':x={3}:y={4}:fontsize={5}:fontcolor={6}\" {7}", videoPath, textMark.FontFile, textMark.Text, textMark.X, textMark.Y, textMark.FontSize, textMark.FontColor.Name.ToLower(), outPath));

// //@"%{localtime\:%Y\-%m\-%d %H-%M-%S}"

//}

/// <summary>

/// 获取视频时长

/// </summary>

/// <param name="sourceFile"></param>

/// <returns></returns>

public static int GetVideoDuration(string sourceFile)

{

//string ffmpegfile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"FFmpeg\ffmpeg.exe";

string ffmpegfile = ConfigHelper.GetConfig().MultimediaFile.Replace("/", "\\") + @"FFmpeg\ffmpeg.exe";

try

{

using (System.Diagnostics.Process ffmpeg = new System.Diagnostics.Process())

{

String duration; // soon will hold our video's duration in the form "HH:MM:SS.UU"

String result; // temp variable holding a string representation of our video's duration

StreamReader errorreader; // StringWriter to hold output from ffmpeg

// we want to execute the process without opening a shell

ffmpeg.StartInfo.UseShellExecute = false;

//ffmpeg.StartInfo.ErrorDialog = false;

ffmpeg.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

// redirect StandardError so we can parse it

// for some reason the output comes through over StandardError

ffmpeg.StartInfo.RedirectStandardError = true;

// set the file name of our process, including the full path

// (as well as quotes, as if you were calling it from the command-line)

ffmpeg.StartInfo.FileName = ffmpegfile;

// set the command-line arguments of our process, including full paths of any files

// (as well as quotes, as if you were passing these arguments on the command-line)

ffmpeg.StartInfo.Arguments = "-i " + sourceFile;

// start the process

ffmpeg.Start();

// now that the process is started, we can redirect output to the StreamReader we defined

errorreader = ffmpeg.StandardError;

// wait until ffmpeg comes back

ffmpeg.WaitForExit();

// read the output from ffmpeg, which for some reason is found in Process.StandardError

result = errorreader.ReadToEnd();

// a little convoluded, this string manipulation...

// working from the inside out, it:

// takes a substring of result, starting from the end of the "Duration: " label contained within,

// (execute "ffmpeg.exe -i somevideofile" on the command-line to verify for yourself that it is there)

// and going the full length of the timestamp

duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);

string[] ss = duration.Split(':');

int h = int.Parse(ss[0]);

int m = int.Parse(ss[1]);

int s = int.Parse(ss[2]);

return h * 3600 + m * 60 + s;

}

}

catch (System.Exception ex)

{

//记录日志

return -1;

}

}

/// <summary>

/// 图片合成视频

/// </summary>

/// <param name="alljpgPath">所有的图片路径</param>

/// <param name="outputMp4Path">输出合成图片视频的所有路径</param>

public static void ImageConvertVideo(string alljpgPath, string outputMp4Path)

{

//string cmd = string.Format(" -i {0} -f segment -segment_time {1} -c copy {2}", targetMp3path, time, outputmp3Path);

//string jpgpath = @"D:\yunyunWork\xinjiang\TestMultiMedia\WindowsFormsApp1\bin\Debug\李梦真\%2d.jpg";

//string mp4path = pathString + string.Format(@"FFmpeg\vedio\o{0}.mp4", Guid.NewGuid().ToString());

string cmd = string.Format("-r 1 -f image2 -i {0} -vcodec libx264 -s 640*480 -g 1 -keyint_min 1 -sc_threshold 0 -pix_fmt yuv420p {1}", alljpgPath, outputMp4Path);

Run1(cmd);

}

/// <summary>

/// 分隔音乐时长

/// </summary>

/// <param name="targetMp3path">目标mp3文件</param>

/// <param name="time">分隔时长</param>

/// <param name="outputmp3Path">输出的目录如</param>

public static void SeparateMusicDuration(string targetMp3path, int time, string outputmp3Path)

{

string cmd = string.Format(" -i {0} -f segment -segment_time {1} -c copy {2}", targetMp3path, time, outputmp3Path);

Run1(cmd);

}

/// <summary>

/// 视频时长大于音乐时长,视频中轮询播放mp3

/// </summary>

/// <param name="inputMp4Path"></param>

/// <param name="mp3Path"></param>

/// <param name="outputMp4Path"></param>

public static void VideoLoopMusic(string inputMp4Path, string mp3Path, string outputMp4Path)

{

string cmd = string.Format("-i {0} -stream_loop -1 -i {1} -filter_complex [0:a][1:a]amix -t 60 -y {2}", inputMp4Path, mp3Path, outputMp4Path);

Run(cmd);

}

/// <summary>

/// 视频中添加音乐

/// </summary>

/// <param name="mp3path">mp3所在的路径</param>

/// <param name="targetMp4Path">需要添加音乐的视频</param>

/// <param name="outputMp4Path">输出添加音乐后的视频</param>

public static void VideoAddMusic(string mp3path, string targetMp4Path, string outputMp4Path)

{

string cmd = string.Format(" -i {0} -i {1} -y {2}", mp3path, targetMp4Path, outputMp4Path);

Run1(cmd);

}

}

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值