使用FFMPEG进行一些视频处理(C#)视频合并、转码、获取时长
FFMPEG的强大无需多说,举几个用到的功能,直接贴代码了
还有更多命令用到时搜索即可
视频转码
public static string DecodeMp4ToFlv(string mp4, string format = ".flv", int timeout = )
{
var args = "-y -i {0} -vcodec copy {1}".Formatting("\"{0}\"".Formatting(mp4), "\"{0}\"".Formatting(strFlvPath));
string output, error;
if (timeout <= )
timeout = **; // 超时时间 = 5 分钟
ProcessHelper.Process(strFFMPEGPath, args, timeout, out output, out error);
if (!error.IsNullOrEmpty())
{
Logger.Error("{0}{1} : {2}{0}".Formatting(Environment.NewLine, "FFmpeg", error));
} return flv;
}
视频合并
public static string ConcatMp4(string mp41, string mp42)
{ var args = " -i \"concat:" + mp41 + "|" + mp42 + "|\" -c copy -bsf:a aac_adtstoasc -movflags +faststart " + outputpath;
string output, error; int timeout = * * ; // 超时时间 = 2 分钟
ProcessHelper.Process(strFFMPEGPath, args, timeout, out output, out error);
if (!error.IsNullOrEmpty())
{
Logger.Error("{0}{1} : {2}{0}".Formatting(Environment.NewLine, "FFmpeg", error));
} return outputpath;
}
获取视频时长
private static int GetVideoDuration(string ffmpegfile, string sourceFile)
{
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[]);
int m = int.Parse(ss[]);
int s = int.Parse(ss[]);
return h * + m * + s;
}
}
catch (System.Exception ex)
{
return ;
}
}
Process处理类如下,也可以自己写个
public static void Process(string startFile, string args, int timeout, out string standardOutput,
out string standardError)
{
using (var process = new ProcessExecutor(startFile, args, timeout))
{
process.Execute(out standardOutput, out standardError);
}
}
internal class ProcessExecutor : IDisposable
{
private readonly StringBuilder error;
private readonly AutoResetEvent errorWaitHandle;
private readonly StringBuilder output;
private readonly int timeout;
private AutoResetEvent outputWaitHandle;
private Process process; public ProcessExecutor(string startFile, string args, int timeout = )
{
process = new Process();
//设置进程启动信息属性StartInfo,这是ProcessStartInfo类
process.StartInfo.FileName = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(startFile));
process.StartInfo.Arguments = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(args)); process.StartInfo.UseShellExecute = false;
//提供的标准输出流只有2k,超过大小会卡住;如果有大量输出,就读出来
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true; output = new StringBuilder();
error = new StringBuilder(); outputWaitHandle = new AutoResetEvent(false);
errorWaitHandle = new AutoResetEvent(false); this.timeout = timeout; RegisterToEvents();
} public void Dispose()
{
UnregisterFromEvents(); if (process != null)
{
process.Dispose();
process = null;
}
if (errorWaitHandle != null)
{
errorWaitHandle.Close();
outputWaitHandle = null;
}
if (outputWaitHandle != null)
{
outputWaitHandle.Close();
outputWaitHandle = null;
}
} public void Execute(out string standardOutput, out string standardError)
{
process.Start(); process.BeginOutputReadLine();
process.BeginErrorReadLine(); if (process.WaitForExit(timeout) &&
outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{ }
else
{
// if timeout then kill the procee
process.Kill();
} standardOutput = output.ToString();
standardError = error.ToString();
} private void RegisterToEvents()
{
process.OutputDataReceived += process_OutputDataReceived;
process.ErrorDataReceived += process_ErrorDataReceived;
} private void UnregisterFromEvents()
{
process.OutputDataReceived -= process_OutputDataReceived;
process.ErrorDataReceived -= process_ErrorDataReceived;
} private void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
} private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
}
}
使用FFMPEG进行一些视频处理(C#)视频合并、转码、获取时长的更多相关文章
- 用阿里官网提供的plupload oss的web直传,视频上传进行前端验证它的时长,尺寸,大小等。替换上一个不需要的单个视频
accessid = '' accesskey = '' host = '' policyBase64 = '' signature = '' callbackbody = '' filename = ...
- ffmreg thinkphp 控制器 获取音频视频详细信息(获取时长)
FFmpeg下载:http://ffmpeg.zeranoe.com/builds/ 下载并解压FFmpeg文件夹: 打开你想安装的任意磁盘,例如:d盘.新建一个名为“ffmpeg”的文件夹,将第二步 ...
- 获取音、视频时长(NAudio,Shell32,FFmpeg)
参考网址:https://blog.csdn.net/u013810234/article/details/57471780 以下为本次测试用到的音.视频格式: audio :”.wav;.mp3;. ...
- FFMpeg 常用命令格式转换,视频合成
FFmpeg都是命令行的,用起来肯定不方便.但是,这对技术宅应该不成问题.下面,我就罗列一些比较实用的使用方法吧. FFmpeg的下载与安装 FFmpeg是开源的.但我们不必去下载它的源代码.下载已经 ...
- js 获取上传视频的时长、大小、后缀名
参考资料:获取时长 var fileName = $("#sectionfileUpload").val(); //C:\fakepath\3.jpeg var exts = fi ...
- 以springMVC为例获取上传视频文件时长
毕设项目是一个在线学习系统,教师用户有上传视频的功能,在答辩之前赶了一个demo出来,好多功能都写死了,比如课程学习进度就是被我写死在前端的一个变量,最近导师要我把项目打包发给他,这才心慌慌赶紧把这些 ...
- android获取mp4视频文件总时长和视频宽高<转>
android使用 MediaMetadataRetriever 获取视频文件的 总时长 和视频的分辨率. 根据该方式获取视频信息可以看出不仅仅可以获取时长和分辨率,还能获取到其他的一些视频信息,不错 ...
- FFmpeg的使用——PHP转换视频、截取视频以及JW Player播放器控制
转载:http://blog.csdn.net/zm2714/article/details/7916440 给朋友做的一个项目中,涉及到上传视频.转换视频.自动截取已上传视频内容中的一帧做为缩略图片 ...
- 新手学习FFmpeg - 调用API完成两个视频的任意合并
本次尝试在视频A中的任意位置插入视频B. 在上一篇中,我们通过调整PTS可以实现视频的加减速.这只是对同一个视频的调转,本次我们尝试对多个视频进行合并处理. Concat如何运行 ffmpeg提供了一 ...
随机推荐
- 从0开始的Python学习006流程控制
流程控制语句 Python中有三种控制流程语句: if.for.和while. if语句 使用if语句来校验一个条件,如果条件为真(True),运行if-块,如果为假(False),运行else-块. ...
- 关于C#传给视图的字符串带有Html转义字符的处理
public class PageBarHelper//分页类 { public static string GetPageBar(string requestHref,int totalCount, ...
- SQL Server数据库————连接查询和分组查询
SQL Server数据库————连接查询和分组查询 分组查询 select 列from <表名> where …… group by 列 注意:跟order by一样group ...
- c/c++ 多线程 一个线程等待某种事件发生
多线程 一个线程等待某种事件发生 背景:某个线程在能够完成其任务之前可能需要等待另一个线程完成其任务. 例如:坐夜间列车,为了能够不坐过站, 1,整夜保持清醒,但是这样你就会非常累,不能够睡觉. 2, ...
- 注册表修改computer name
修改windows server的机器名的时候,发现change按钮是disable的. 手动修改不了,用注册表regedit来修改. HKEY_LOCAL_MACHINE\SYSTEM\Curren ...
- nginx内置变量总结
nginx内置变量 2019-02-28 变量名称 变量用途 $atg_PARAMETER 客户端GET请求中 PARAMETER字段的值 ...
- docker swarm的常用操作
1. 说明 本文档针对docker swarm操作. 针对的系统是以一个本地的测试系统为例.其中机器信息如下,172.16.1.13作为docker swarm的管理机. 本地测试的机器列表信息: 主 ...
- display:inline-block,block,inline的区别与用法
一.首先要了解什么是块级元素与行级元素 块级元素 会占领页面的一行,其后多个block元素自动换行. 可以设置width,height,设置了width后同样也占领一行.同样也可以设置 margi ...
- AI pytorch
pytorch 参考链接: https://pytorch.org
- 微信小程序 初步认识一(微信运动步数)
1.注册微信小程序 2.安装小程序开发工具 3.实例(显示微信运动步数) 4.后端处理(c#) 一 注册微信小程序 注册地址:https://mp.weixin.qq.com/cgi-bin/regi ...