using DirectShowLib;
using DirectShowLib.DES;
using System.Runtime.InteropServices;
...
var mediaDet = (IMediaDet)new MediaDet();
DsError.ThrowExceptionForHR(mediaDet.put_Filename(FileName));
// find the video stream in the file
int index;
var type = Guid.Empty;
for (index = 0; index < 1000 && type != MediaType.Video; index++)
{
mediaDet.put_CurrentStream(index);
mediaDet.get_StreamType(out type);
}
// retrieve some measurements from the video
double frameRate;
mediaDet.get_FrameRate(out frameRate);
var mediaType = new AMMediaType();
mediaDet.get_StreamMediaType(mediaType);
var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
DsUtils.FreeAMMediaType(mediaType);
var width = videoInfo.BmiHeader.Width;
var height = videoInfo.BmiHeader.Height;
double mediaLength;
mediaDet.get_StreamLength(out mediaLength);
var frameCount = (int)(frameRate * mediaLength);
var duration = frameCount / frameRate;
更为简单的方式是调用ffmpeg, ffmpeg -i一下,需要什么信息,解析一下输出内容就好了。
public static string getTime(string path)
{
try
{
Shell32.Shell shell = new Shell32.ShellClass();
//文件路径
Shell32.Folder folder = shell.NameSpace( path.Substring(0, path.LastIndexOf("\\")));
//文件名称
Shell32.FolderItem folderitem = folder.ParseName(path.Substring(path.LastIndexOf("\\") + 1));
return folder.GetDetailsOf(folderitem, 21);
}
catch (Exception ex)
{
return null;
}
}
在引用 COM 接口里 引用一下Microsoft Shell Controls And Automation 1.0
然后把引用后文件的 嵌入互操作类型, ,改成false 就可以了。