Skip to content

Instantly share code, notes, and snippets.

@ericpony
Last active November 25, 2022 17:27
Show Gist options
  • Save ericpony/e788f80b3a639ed8e0a1 to your computer and use it in GitHub Desktop.
Save ericpony/e788f80b3a639ed8e0a1 to your computer and use it in GitHub Desktop.
Retrieve media info using C#
/*
* http://stackoverflow.com/questions/6215185/getting-length-of-video
*/
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;
///////////////////////////////
// Version 2
///////////////////////////////
using WMPLib;
WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMedia mediainfo = wmp.newMedia(file);
var duration = mediainfo.duration;
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment