MZimmerman6 MZimmerman6 - 5 months ago 68
C# Question

Getting length of video

I am having trouble finding a simple example of how to get the video length of a file programmatically. Many people say, oh use this library/wrapper or whatever, but do not say how. I have downloaded ffmpeg, but have no clue how to actually use it and there does not seem to be any example of how to use it to get the video duration. I see how you can use it to convert videos, but I simply just want to know the duration of a video. All of the other information does not matter.

Is there any way of doing this simply, whether it be in C#, python, java, whatever, that will just return a string that indicates the length of a video file.

Please provide examples if possible. Thanks in advance!

Assume standard file formats, such as wmv, avi, mp4, mpeg. Stuff that has metadata.


Here is an example:

using DirectShowLib;
using DirectShowLib.DES;
using System.Runtime.InteropServices;


var mediaDet = (IMediaDet)new MediaDet();

// find the video stream in the file
int index;
var type = Guid.Empty;
for (index = 0; index < 1000 && type != MediaType.Video; index++)
    mediaDet.get_StreamType(out type);

// retrieve some measurements from the video
double frameRate;
mediaDet.get_FrameRate(out frameRate);

var mediaType = new AMMediaType();
var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
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;