Retreiving the duration of a WMV in C#

This week, I needed to get read the duration of a few hundred Windows
Media Video files for a project. Since I started my development code in
ASP and then ASP.NET, I pretty much only know managed code, so I wanted
to use a .NET language. I searched google.com for "wmv duration" and
"wmv duration C#" and came up with nothing. I found the 10 different
Windows Media SDKs, 9 different DirectX SDKs, and a several forum posts
asking the question "How can I read the duration of a WMV/WMA in C#",
but no answers.

I finally found this post on windows.public.windowsmedia.sdk.  It wasn't quite right, but it got me where I needed to go.

Here's the final code:

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)) );
}

That's it.

10 thoughts on “Retreiving the duration of a WMV in C#

  1. Thanks John… helped me a lot. I’m new to the MS-programming-world but "imports" – isn’t that VB-code? Shouldn’t it read "using"?

  2. Thanks for this code snippet! It is just what I needed!!! Luckly Skooter found this 3 year old post since that probably boosted its relevance enough for me to find this in Google.
    For some reason though, this fails with a "Unable to cast COM object of type…" when I try to call media.duration. The attributeCount, getAttributeName, and getItemInfo methods all work fine though.
    IWMPMedia media = player.newMedia(filepath);
    duration = media.duration;
    Equally strange is that I can get the duration with:
    duration = player.newMedia(filepath).duration;

  3. This code works fine in local machine,but when i upload to the server it shows duration=00:00.
    why??
    I am not getting..
    please help me

  4. This code works fine in local machine,but when i upload to the server it shows duration=00:00.
    here is the code
    WindowsMediaPlayer wmp = new WindowsMediaPlayer();
    IWMPMedia mediaInfo = wmp.newMedia(FileUpload1.PostedFile.FileName);
    Response.Write("Duration = " + mediaInfo.durationString
    why it is not calculating the duration in the server??

  5. i am getting following error.
    1) Interop type ‘WMPLib.WindowsMediaPlayerClass’ cannot be embedded.
    2) The type ‘WMPLib.WindowsMediaPlayerClass’ has no constructors defined

Comments are closed.