【C#获取音频文件的播放时间】
[DllImport("Kernel32", CharSet = CharSet.Auto)]
static extern Int32 GetShortPathName(String path, StringBuilder shortPath, Int32 shortPathLength);
[DllImport("winmm.dll")]
public static extern int mciSendString(string m_strCmd, StringBuilder m_strReceive, int m_v1, int m_v2);
private string getasfTime(string filePath)
{
StringBuilder shortpath = new StringBuilder(80);
GetShortPathName(filePath, shortpath, shortpath.Capacity);
string name = shortpath.ToString();
StringBuilder buf = new StringBuilder(80);
mciSendString("close all", buf, buf.Capacity, 0);
mciSendString("open " + name + " alias media", buf, buf.Capacity, 0);
mciSendString("status media length", buf, buf.Capacity, 0);
TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)Convert.ToDouble(buf.ToString().Trim()));
return ts.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.Text = getasfTime("F:\\视频\\游戏视频-贼法竞技场2v2 2200+.avi");
}
注:该程序段能获取的音频或者视频的格式由 [DllImport("winmm.dll")]中的winmm。dll决定。当然可以导入其他dll文件来支持其他格式。但其中函数也随之变化。
添加引用SHELL32.DLL
public static class GetVideoLength
{
public static string GetMediaTimeLen(string path)
{
try
{
Shell32.Shell shell = new Shell32.Shell();
//文件路径
Shell32.Folder folder = shell.NameSpace(path.Substring(0, path.LastIndexOf("\\")));
//文件名称
Shell32.FolderItem folderitem = folder.ParseName(path.Substring(path.LastIndexOf("\\") + 2));
if (Environment.OSVersion.Version.Major >= 6)
{
return folder.GetDetailsOf(folderitem, 27);
}
else
{
return folder.GetDetailsOf(folderitem, 21);
}
}
catch (Exception ex) { return null; }
}
public static int GetMediaTimeLenSecond(string path)
{
try
{
Shell32.Shell shell = new Shell32.Shell();
//文件路径
Shell32.Folder folder = shell.NameSpace(path.Substring(0, path.LastIndexOf("\\")));
//文件名称
Shell32.FolderItem folderitem = folder.ParseName(path.Substring(path.LastIndexOf("\\") + 2));
string len;
if (Environment.OSVersion.Version.Major >= 6)
{
len = folder.GetDetailsOf(folderitem, 27);
}
else
{
len = folder.GetDetailsOf(folderitem, 21);
}
string[] str = len.Split(new char[] { ':' });
int sum = 0;
sum = int.Parse(str[0]) * 60 * 60 + int.Parse(str[1]) * 60 + int.Parse(str[2]);
return sum;
}
catch (Exception ex) { return 0; }
}
}