使用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提供了一 ...
随机推荐
- The account that is running SQL Server Setup does not have one or all of the following rights: the right to back up files and directories, the right to manage auditing and the security log and the rig
安装SQL SERVER 是规则检查提示权限问题 运行secpol.msc,没有Debug program权限,添加即可,如果已加域则要在域策略修改,或退域安装后在加域.
- 【公众号系列】SAP HANA 平台的优势
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[公众号系列]SAP HANA 平台的优势 ...
- OKR相关4本书,好书3本
最近几年看过4本OKR相关的书,有3本是4星.其中第一本是最近看的,剩下3本是2017年看的. OKR源自德鲁克和格鲁夫,跟谷歌是天作之合:4星|<这就是OKR> 4星|<OKR实践 ...
- Nginx 配置 https
从云服务提供商处申请证书 申请 https 证书教程-百度经验 申请下来的证书目录结构 . ├── Apache │ ├── 1_root_bundle.crt │ ├── 2_website ...
- WebDriverAgent入门篇-安装和使用
前言 在群里看到WebDriverAgent这个东西,出于好奇,便开始百度+谷歌,最终对其有了简单的了解.也对自动化测试也有了一个初步的了解.接下来你看到的是对WebDriverAgent的一些介绍. ...
- springMVC使用HandlerMethodArgumentResolver 自定义解析器实现请求参数绑定方法参数
http://blog.csdn.net/truong/article/details/30971317 http://blog.csdn.net/fytain/article/details/439 ...
- Flink Pre-defined Timestamp Extractors / Watermark Emitters(预定义的时间戳提取/水位线发射器)
https://ci.apache.org/projects/flink/flink-docs-release-1.6/dev/event_timestamp_extractors.html 根据官网 ...
- 分布式任务调度平台XXL-JOB搭建教程
关于分布式任务调度平台XXL-JOB,其实作者 许雪里 在其发布的中文教程中已经介绍的很清楚了,这里我就不做过多的介绍了,关于其搭建教程,本人依照其文档搭建起来基本上也没遇到啥问题,这里通过博客的形式 ...
- Winform开发框架中工作流模块的动态处理
在工作流处理表中,首先我们区分流程模板和流程实例两个部分,这个其实就是类似模板和具体文档的概念,我们一份模板可以创建很多个类似的文档,文档样式结构类似的.同理,流程模板实例为流程实例后,就是具体的一个 ...
- 【翻译】WhatsApp 加密概述(技术白皮书)
目录 简介 术语 客户端注册 会话初始化设置 接收会话设置 交换信息 传输媒体和附件 群组消息 通话设置 ...