How to get video duration from mp4, wmv, flv, mov videos

67,138

Solution 1

You can use DirectShow API MediaDet object, through DirectShow.NET wrapper library. See Getting length of video for code sample, get_StreamLength gets you the duration in seconds. This assumes Windows has MPEG-4 demultiplexer installed (requires third party components with Windows prior to 7, I believe the same applies to another answer by cezor, there are free to redistribute components though).

Solution 2

This answer about P/Invoke for Shell32 reminded me of the Windows API Code Pack to access common Windows Vista/7/2008/2008R2 APIs.

It was very easy, using the PropertyEdit demo in the included samples, to figure out the Shell32 API to get various media file properties, like duration.

I assume the same prerequisite applies for having the proper demultiplexers installed, but it was quite simple, as it only required adding references to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll and the following code:

using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;

using (ShellObject shell = ShellObject.FromParsingName(filePath))
{
    // alternatively: shell.Properties.GetProperty("System.Media.Duration");
    IShellProperty prop = shell.Properties.System.Media.Duration; 
    // Duration will be formatted as 00:44:08
    string duration = prop.FormatForDisplay(PropertyDescriptionFormatOptions.None);
}

Other stuff

Some common properties for an MPEG-4/AAC audio media file:

System.Audio.Format = {00001610-0000-0010-8000-00AA00389B71}
System.Media.Duration = 00:44:08
System.Audio.EncodingBitrate = ?56kbps
System.Audio.SampleRate = ?32 kHz
System.Audio.SampleSize = ?16 bit
System.Audio.ChannelCount = 2 (stereo)
System.Audio.StreamNumber = 1
System.DRM.IsProtected = No
System.KindText = Music
System.Kind = Music

It's easy to iterate through all properties if you're looking for the available metadata:

using (ShellPropertyCollection properties = new ShellPropertyCollection(filePath))
{
    foreach (IShellProperty prop in properties)
    {
        string value = (prop.ValueAsObject == null) ? "" : prop.FormatForDisplay(PropertyDescriptionFormatOptions.None);
        Console.WriteLine("{0} = {1}", prop.CanonicalName, value);
    }
}

Solution 3

You could also use windows media player, although it don't support alle file types you requested

using WMPLib;

public Double Duration(String file)
    {
        WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
        IWMPMedia mediainfo = wmp.newMedia(file);
        return mediainfo.duration;
    }
}

Solution 4

IMHO you could use MediaInfo which gives you a lot of information about media files.
There is a CLI for it so you can use it from your code and get info you need.
You can take a look at this link.

Solution 5

I think you are looking for FFMPEG - https://ffmpeg.org/

there are also some free alternatives that you can read about them in this question - Using FFmpeg in .net?

   FFMpeg.NET
   FFMpeg-Sharp
   FFLib.NET

you can see this link for examples of using FFMPEG and finding the duration - http://jasonjano.wordpress.com/2010/02/09/a-simple-c-wrapper-for-ffmpeg/

        public VideoFile GetVideoInfo(string inputPath)
        {
            VideoFile vf = null;
            try
            {
                vf = new VideoFile(inputPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            GetVideoInfo(vf);
            return vf;
        }
        public void GetVideoInfo(VideoFile input)
        {
            //set up the parameters for video info
            string Params = string.Format("-i {0}", input.Path);
            string output = RunProcess(Params);
            input.RawInfo = output;

            //get duration
            Regex re = new Regex("[D|d]uration:.((\\d|:|\\.)*)");
            Match m = re.Match(input.RawInfo);

            if (m.Success)
            {
                string duration = m.Groups[1].Value;
                string[] timepieces = duration.Split(new char[] { ':', '.' });
                if (timepieces.Length == 4)
                {
                    input.Duration = new TimeSpan(0, Convert.ToInt16(timepieces[0]), Convert.ToInt16(timepieces[1]), Convert.ToInt16(timepieces[2]), Convert.ToInt16(timepieces[3]));
                }
            }
       }
Share:
67,138
MonsterMMORPG
Author by

MonsterMMORPG

Hello. I am the only owner and developer of web based online MMORPG game MonsterMMORPG. I am a computer engineer from Turkey and i am currently doing MA at computer engineering. I am specialized with C# & ASP.net. http://www.monstermmorpg.com/ MonsterMMORPG is a Free To Play Browser Based Online Monster MMORPG Game Better Than Online Pokemon Games You will love it's awesome Monsters We have many different unique features. So i suggest you to check them out. Our game is similiar with Pokemon games but it is unique. Like diablo and torch light. You should visit following sites related to us MonsterMMORPG Facebook Pokemon Games Lovers Facebook Application MonsterMMORPG Youtube Channel Monster Game Forum Canavar Oyunu Forum Pokemon Fakemon DeviantArt MonsterMMORPG Google Plus MonsterMMORPG Twitter MonsterMMORPG Review On Browsergamez MonsterMMORPG Review On mmohuts MonsterMMORPG Developer Blog At MMORPG.com MonsterMMORPG Review On onrpg MonsterMMORPG On GameSpot MonsterMMORPG Wiki MonsterMMORPG On 1UP MonsterMMORPG Digg MonsterMMORPG Official Google Plus Page

Updated on August 19, 2020

Comments

  • MonsterMMORPG
    MonsterMMORPG almost 4 years

    Alright. Actually i need mostly the mp4 format. But if it is possible to get for other types as well that would be nice. I just need to read the duration of the file. How can i do that with C# 4.0 ?

    So the thing i need is like this video is like : 13 minutes 12 seconds

    I can use 3 third party exes too. Like they save the information about the file to a text file. I can parse that text file.

    Thank you.