c# 获取MP3和AMR文件格式的时长

时间:2023-03-08 23:32:41
c# 获取MP3和AMR文件格式的时长
//网上摘录整理
private long GetAMRFileDuration(string fileName)
{
long duration = ;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
{
byte[] packed_size = new byte[] { , , , , , , , , , , , , , , , };
int pos = ;
pos += ;
long lenth = fs.Length;
byte[] toc = new byte[];
int framecount = ;
byte ft;
while (pos < lenth)
{
fs.Seek(pos, SeekOrigin.Begin);
if ( != fs.Read(toc, , ))
{
duration = lenth > ? ((lenth - ) / ) : ;
fs.Close();
break;
}
ft = (byte)((toc[] / ) & 0x0F);
pos += packed_size[ft] + ;
framecount++;
}
duration = framecount * / ;
}
fs.Close();
return duration;
}     //添加引用:COM组件的Microsoft Shell Controls And Automation
    //然后引用 using Shell32;
    //如果出现“无法嵌入互操作类型 请改用适用的接口”报错————修改引用里面的shell32属性嵌入互操作类型改为false
private long GetMP3FileDuration(string fileName)
{
ShellClass sh = new ShellClass();
Folder dir = sh.NameSpace(Path.GetDirectoryName(fileName));
FolderItem item = dir.ParseName(Path.GetFileName(fileName));
string str = dir.GetDetailsOf(item, ); // 获取歌曲时长。 var matchs = Regex.Match(str, @"(\d{2}):(\d{2}):(\d{2})");
var hour = nt.PubTool.Comm.ConvertTo.ToInt32(matchs.Groups[].Value);
var minute = nt.PubTool.Comm.ConvertTo.ToInt32(matchs.Groups[].Value);
var second = nt.PubTool.Comm.ConvertTo.ToInt32(matchs.Groups[].Value); var len = hour * + minute * + second;
return len; }