How do I get the duration of a video file using C#

2019-09-15 18:01发布

问题:

Any library in C# that allows me to do that?

回答1:

google result for http://johndyer.name/post/2005/07/22/Retreiving-the-duration-of-a-WMV-in-C.aspx

using WMPLib; // this file is called Interop.WMPLib.dll

WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia("myfile.wmv"); 

// write duration
Console.WriteLine("Duration = " + mediaInfo.duration);

// write named attributes
for (int i=0; i<mediaInfo.attributeCount; i++)
{
Console.WriteLine(mediaInfo.getAttributeName(i) + " = " +  mediaInfo.getItemInfo(mediaInfo.getAttributeName(i)) );
}


回答2:

You can try this Extension method.

using Shell32;

public static class Extension
{
    public static string GetLength(this FileInfo info)
    {
        var shell = new ShellClass();
        var folder = shell.NameSpace(info.DirectoryName);
        var item = folder.ParseName(info.Name);

        return folder.GetDetailsOf(item, 27);
    }
}


回答3:

I hope following code snippet will help you :

using WMPLib;
// ...your code here...

var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));

and don't forget to add the reference of wmp.dll which will be present in System32 folder.