C#-C# 如何知道一个影像文件能够播放多长时间

C#-C# 如何知道一个影像文件能够播放多长时间

甜柠檬 发布于 2016-11-04 字数 0 浏览 963 回复 3

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

想挽留 2017-08-30 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一下,需要什么信息,解析一下输出内容就好了。

夜无邪 2017-06-24 2 楼

使用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();
}