获取音、视频时长(NAudio,Shell32,FFmpeg)
参考网址:https://blog.csdn.net/u013810234/article/details/57471780
以下为本次测试用到的音、视频格式:
audio :”.wav;.mp3;.wma;.ra;.mid;.ogg;.ape;.au;.aac;”;
vedio :”.mp4;.mpg;.mpeg;.avi;.rm;.rmvb;.wmv;.3gp;.flv;.mkv;.swf;.asf;”;
Note:
1. 测试音、视频均为对应格式的有效文件(下载自地址:包含了各种可供测试音视频格式,且不断更新中。。);
2. 若某音/视频时长为0,表示对应库、组件无法解码文件,即不支持该格式;
3. 类之间的关系:定义了Duration父类,三个测试方案均继承自Duration,并重写父类GetDuration方法。
获取时长父类
public abstract class Duration
{
/// <summary>
/// Abstract method of getting duration(ms) of audio or vedio
/// </summary>
/// <param name="filePath">audio/vedio's path</param>
/// <returns>Duration in original format, duration in milliseconds</returns>
public abstract Tuple<string, long> GetDuration(string filePath);
/// <summary>
/// Convert format of "00:10:16" and "00:00:19.82" into milliseconds
/// </summary>
/// <param name="formatTime"></param>
/// <returns>Time in milliseconds</returns>
public long GetTimeInMillisecond(string formatTime)
{
double totalMilliSecends = 0;
if (!string.IsNullOrEmpty(formatTime))
{
string[] timeParts = formatTime.Split(':');
totalMilliSecends = Convert.ToInt16(timeParts[0]) * 60 * 60 * 1000
+ Convert.ToInt16(timeParts[1]) * 60 * 1000
+ Math.Round(double.Parse(timeParts[2]) * 1000);
}
return (long)totalMilliSecends;
}
}
使用NAudio.dll
下载、引用NAudio.dll;
由于NAudio本身主要用于处理音频,用其获取视频时长并不合理(仅作统一测试),所以多数格式不支持,不足为奇;
public class ByNAudio : Duration
{
/// <summary>
/// Get duration(ms) of audio or vedio by NAudio.dll
/// </summary>
/// <param name="filePath">audio/vedio's path</param>
/// <returns>Duration in original format, duration in milliseconds</returns>
/// <remarks>return value from NAudio.dll is in format of: "00:00:19.820"</remarks>
public override Tuple<string, long> GetDuration(string filePath)
{
TimeSpan ts;
try
{
using (AudioFileReader audioFileReader = new AudioFileReader(filePath))
{
ts = audioFileReader.TotalTime;
}
}
catch (Exception)
{
/* As NAudio is mainly used for processing audio, so some formats may not surport,
* just use 00:00:00 instead for these cases.
*/
ts = new TimeSpan();
//throw ex;
}
return Tuple.Create(ts.ToString(), GetTimeInMillisecond(ts.ToString()));
}
}
NAudio结果:
使用Shell32.dll
引用Shell32.dll,在COM里;
Windows自带的组件,仅支持常见的音视频格式;
public class ByShell32 : Duration
{
/// <summary>
/// Get duration(ms) of audio or vedio by Shell32.dll
/// </summary>
/// <param name="filePath">audio/vedio's path</param>
/// <returns>Duration in original format, duration in milliseconds</returns>
/// <remarks>return value from Shell32.dll is in format of: "00:10:16"</remarks>
public override Tuple<string, long> GetDuration(string filePath)
{
try
{
string dir = Path.GetDirectoryName(filePath);
// From Add Reference --> COM
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder folder = shell.NameSpace(dir);
Shell32.FolderItem folderitem = folder.ParseName(Path.GetFileName(filePath));
string duration = null;
// Deal with different versions of OS
if (Environment.OSVersion.Version.Major >= 6)
{
duration = folder.GetDetailsOf(folderitem, 27);
}
else
{
duration = folder.GetDetailsOf(folderitem, 21);
}
duration = string.IsNullOrEmpty(duration) ? "00:00:00" : duration;
return Tuple.Create(duration, GetTimeInMillisecond(duration));
}
catch (Exception ex)
{
throw ex;
}
}
}
Shell32结果:
使用FFmpeg.exe
下载FFmpeg.exe;
异步调用“ffmpeg -i 文件路径”命令,获取返回文本,并解析出Duration部分;
FFmpeg是对音视频进行各种处理的一套完整解决方案,包含了非常先进的音频/视频编解码库,因此可处理多种格式(本次测试的音、视频格式均可以进行有效解码)。
public class ByFFmpeg : Duration
{
private StringBuilder result = new StringBuilder(); // Store output text of ffmpeg
/// <summary>
/// Get duration(ms) of audio or vedio by FFmpeg.exe
/// </summary>
/// <param name="filePath">audio/vedio's path</param>
/// <returns>Duration in original format, duration in milliseconds</returns>
/// <remarks>return value from FFmpeg.exe is in format of: "00:00:19.82"</remarks>
public override Tuple<string, long> GetDuration(string filePath)
{
GetMediaInfo(filePath);
string duration = MatchDuration(result.ToString());
return Tuple.Create(duration, GetTimeInMillisecond(duration));
}
// Call exe async
private void GetMediaInfo(string filePath)
{
result.Clear(); // Clear result to avoid previous value's interference
Process p = new Process();
p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = string.Concat("-i ", filePath);
p.ErrorDataReceived += new DataReceivedEventHandler(OutputCallback);
p.Start();
p.BeginErrorReadLine();
p.WaitForExit();
p.Close();
p.Dispose();
}
// Callback funciton of output stream
private void OutputCallback(object sender, DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
{
result.Append(e.Data);
}
}
// Match the 'Duration' section in "ffmpeg -i filepath" output text
private string MatchDuration(string text)
{
string pattern = @"Duration:\s(\d{2}:\d{2}:\d{2}.\d+)";
Match m = Regex.Match(text, pattern);
return m.Groups.Count == 2 ? m.Groups[1].ToString() : string.Empty;
}
}
ffmpeg -i filePath
……[mp3 @ 0233ca60] Estimating duration from bitrate, this may be inaccurate
Input #0, mp3, from ‘2012.mp3’:
Duration: 00:22:47.07, start: 0.000000, bitrate: 127 kb/s
Stream #0:0: Audio: mp3, 44100 Hz, stereo, s16p, 128 kb/s
At least one output file must be specified
Note:以上为ffmpeg -i 命令的输出值,需要匹配到Duration的时长部分。
FFmpeg结果:
Source Code(含测试音、视频文件): Github
获取音、视频时长(NAudio,Shell32,FFmpeg)的更多相关文章
- asp.net 获取音视频时长 的方法
http://www.evernote.com/l/AHPMEDnEd65A7ot_DbEP4C47QsPDYLhYdYg/ 日志: 1.第一种方法: 调用:shell32.dll ,win7 ...
- jave 计算音视频时长
File source = new File("视频.mp4"); Encoder encoder = new Encoder(); try { MultimediaInfo in ...
- vue / js使用video获取视频时长
项目中遇到上传视频功能,需要有预览和获取视频时长功能,因之前使用upload(有需要的话可以参考下我之前的文章),这里就不赘述,直接用来上传视频,不过在上传之前和上传成功后的钩子里,获取不到时长: 没 ...
- vue 获取视频时长
参考资料:js获取上传音视频文件的时长 直接通过element-ui自带的上传组件结合js即可,代码如下: HTML: <el-upload class="upload-demo&qu ...
- windows server 2008 R2服务器无法通过ShellClass获取mp3音乐时长
我们先看一段代码,获取mp3播放时长: #region GetMediaDetailInfo 获取媒体文件属性信息 /// <summary> /// 获取媒体文件属性信息 /// < ...
- iOS:Gif动画功能(显示gif动画、获取gif动画时长、获取gif动画执行次数)
一.简单介绍 gif动画是iOS开发中很常用的一个功能,有的是为了显示加载视频的过程,更多的是为了显示一个结果状态(动画更直观). 那么如何执行gif动画,方法有很多.(这里只写一下方法三,前两种之前 ...
- Android获取视频音频的时长的方法
android当中获取视频音频的时长,我列举了三种. 1:获取视频URI后获取cursor cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore ...
- Long类型时间如何转换成视频时长?
数据库中存放的视频时长是一个Long类型的毫秒/秒时间,现在需要把这个时间转换成标准的视频时长格式,在我看来这应该是一个很常用的转化有一个很常用的转换方法工具才对,可是我百度找了许久,没有一个简单直观 ...
- javascript 获得以秒计的视频时长
<!DOCTYPE html> <html> <body> <h3>演示如何访问 VIDEO 元素</h3> <video id=&q ...
随机推荐
- long long 与__int64
//为了和DSP兼容,TSint64和TUint64设置成TSint40和TUint40一样的数 //结果VC中还是认为是32位的,显然不合适 //typedef signed long int ...
- vue中使用vw适配移动端
推荐看看大漠老师的文章,非常的有收获 如何在Vue项目中使用vw实现移动端适配 1.首先在项目中安装依赖 npm i postcss-aspect-ratio-mini postcss-px-to-v ...
- django生成迁移文件
1.创建虚拟环境 在终端上输入创建python3的虚拟环境 mkvirtualenv -p python3 虚拟环境的名字 安装django和pymysql 2.创建项目创建工程的命令: django ...
- Python&HDF5目录
最近一直没更新python&量化的博客,是因为忙于看HDF5的书,写VNPY框架,学scrapy爬虫. 本来写博客的目的就是为了当作一种教材,当遇到不会的问题过来找答案. 对于HDF5下面这本 ...
- 第 6 章 存储 - 044 - volume 生命周期管理
volume 生命周期管理 1)备份 因为 volume 实际上是 host 文件系统中的目录和文件,所以 volume 的备份实际上是对文件系统的备份 例如:本地的Registry,所有镜像都存在/ ...
- 利用WCF实现上传下载文件服务
使用WCF上传文件 在WCF没出现之前,我一直使用用WebService来上传文件,我不知道别人为什么要这么做,因为我们的文件服务器和网站后台和网站前台都不在同一个机器,操作人员觉 ...
- 百度基础架构组-实习生面试(2016.08 java后台开发)
一.项目 1.Spring MVC与Struts2的区别: 2.MVC三层是如何工作的?比如:要访问一个Url?a=xx&b=xx,怎么找到相应的资源,怎么运算,怎么返回等? 3.数据库myb ...
- java把类似a=1&b=2&c=3的String类型数据转成map集合
public static Map<String, Object> transStringToMap(String mapString, String separator, String ...
- js事件流 事件捕获 及时间冒泡详解
Javascript与HTML之间的交互是通过事件实现. 一.事件流 事件,是文档或浏览器窗口中发生的一些特定的交互瞬间.事件流,描述的是页面中接受事件的顺序.IE9,chrome,Firefox,O ...
- Ubuntu下忘记MySQL root密码解决方法
1.忘了mysql密码,从网上找到的解决方案记录在这里. 编辑mysql的配置文件/etc/mysql/my.cnf,在[mysqld]段下加入一行“skip-grant-tables”. 2.重启服 ...