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;
发布评论
评论(3)
分享给你一段代码吧
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一下,需要什么信息,解析一下输出内容就好了。
使用winmm库就能方便取到这个信息的:
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetShortPathName(
string lpszLongPath,
string shortFile,
int cchBuffer
);
[DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)]
public static extern int mciSendString(
string lpstrCommand,
string lpstrReturnString,
int uReturnLength,
int hwndCallback
);
private string getLastTime(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 + " type mpegvideo 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();
}
原问题,解答链接:如何用C#代码 获取一个视频的播放时长,先谢谢各位大牛小牛了