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

10

28

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.

Reprehensible answered 17/4, 2012 at 12:5 Comment(0)
C
12

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).

Coil answered 17/4, 2012 at 12:27 Comment(7)
Where is this DirectShot API ? Can you also give me the url of this third part ? Or do you mean like k lite mega codec pack ?Peppercorn
Thanks this line gives the correct duration as seconds : mediaDet.get_StreamLength(out mediaLength);Peppercorn
DirectShow is core Windows API, you always have it. Wrapper library directshownet.sourceforge.net is your C# bridge to DriectShow. The problem with MP4 files is that you need to have a demultiplexer installed. As it is patented technology, this brings troubles into life - there is no one by default. A good installable/redistributable option is there gdcl.co.uk/mpeg4 You only need to figure out how to redist and install it.Coil
Alright this failed at windows server 2008 r2 but working at my local computer. What do i need to install windows server ? Would k lite mega codec pack work ?Peppercorn
Yes, I believe so. Or, use the link above from GCDL. You need to take DLLs from there and regsvr32 them inthe target system - this should be sufficient.Coil
I suppose the cause of error is IMediaDet. It seems like windows server 2008 r2 does not have that ? Please take a look at this error : img705.imageshack.us/img705/7446/error2od.pngPeppercorn
Yes, I'd suppose the same. I was under impression it was missing in early builds of Server 2008 and than returned back into place, groups.google.com/group/…Coil
E
18

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);
    }
}
Excitable answered 16/9, 2013 at 0:51 Comment(2)
Pretty neat, but the duration resolution is seconds - I need the fractions, too. Note for anyone trying this, you'll need to add NuGet references to Windows7APICodePack-Core/Shell.Rudy
love it :) I'm all about the CodePack at this point. Note the raw value for the property appears to be specifically 10^-7 seconds... I don't know if that much detail is actually provided for all file types, but you can look for it. The raw value is in property ".ValueAsObject" and it's a ulong you need to cast out of a generic Object. I'll edit the answer to try to add this.Airmail
F
17

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;
    }
}
Frisky answered 17/4, 2012 at 12:19 Comment(2)
Thanks but the application will work on windows server 2008. I suppose they don't have windows media player.Peppercorn
@MonsterMMORPG Looks like you're right https://mcmap.net/q/503369/-could-not-load-file-or-assembly-39-axinterop-wmplib-39-or-one-of-its-dependencies-the-parameter-is-incorrectRules
C
12

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).

Coil answered 17/4, 2012 at 12:27 Comment(7)
Where is this DirectShot API ? Can you also give me the url of this third part ? Or do you mean like k lite mega codec pack ?Peppercorn
Thanks this line gives the correct duration as seconds : mediaDet.get_StreamLength(out mediaLength);Peppercorn
DirectShow is core Windows API, you always have it. Wrapper library directshownet.sourceforge.net is your C# bridge to DriectShow. The problem with MP4 files is that you need to have a demultiplexer installed. As it is patented technology, this brings troubles into life - there is no one by default. A good installable/redistributable option is there gdcl.co.uk/mpeg4 You only need to figure out how to redist and install it.Coil
Alright this failed at windows server 2008 r2 but working at my local computer. What do i need to install windows server ? Would k lite mega codec pack work ?Peppercorn
Yes, I believe so. Or, use the link above from GCDL. You need to take DLLs from there and regsvr32 them inthe target system - this should be sufficient.Coil
I suppose the cause of error is IMediaDet. It seems like windows server 2008 r2 does not have that ? Please take a look at this error : img705.imageshack.us/img705/7446/error2od.pngPeppercorn
Yes, I'd suppose the same. I was under impression it was missing in early builds of Server 2008 and than returned back into place, groups.google.com/group/…Coil
L
5

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.

Lavadalavage answered 17/4, 2012 at 12:9 Comment(2)
Hello. I am not able to add the mediainfodll as a reference. Do you know why ? Here error message : img707.imageshack.us/img707/8130/hataow.pngPeppercorn
@MonsterMMORPG: you must call application with params and get output, can't use it as a reference inside your solutionLavadalavage
I
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]));
                }
            }
       }
Illume answered 17/4, 2012 at 12:9 Comment(2)
This is a pay to have application. They provide only trial. This would not work for me :(Peppercorn
@MonsterMMORPG ffrmpeg is a free software! see: ffmpeg.org/legal.htmlLuckless
W
3

FFMPEG project has a tool, called ffprobe which can provide you the information you need about your multimedia files and ouput the information in a nicely formated JSON.

Take a look at this answer for an example.

Wurster answered 29/5, 2013 at 6:58 Comment(0)
S
3

Using Windows Media Player Component also, we can get the duration of the video.
Following code snippet may help you guys :

using WMPLib;
// ...
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.

Sheffield answered 2/9, 2016 at 1:11 Comment(0)
P
2

I found the NReco.VideoInfo library to be the best option and far simpler than some of those above. It's a simple as giving the library a file path and it spits out the metadata:

var ffProbe = new FFProbe();
var videoInfo = ffProbe.GetMediaInfo(blob.Uri.AbsoluteUri);
return videoInfo.Duration.TotalMilliseconds;
Pettish answered 13/11, 2015 at 13:55 Comment(1)
Just note Commercial Use has a paid license on this oneGorgonian
F
1

I had the same problem and we built a wrapper for ffprobe Alturos.VideoInfo. You can use it simply by installing the nuget package. Also the ffprobe binary is required.

PM> install-package Alturos.VideoInfo

Example

var videoFilePath = "myVideo.mp4";

var videoAnalyer = new VideoAnalyzer("ffprobe.exe");
var analyzeResult = videoAnalyer.GetVideoInfo(videoFilePath);

var duration = analyzeResult.VideoInfo.Format.Duration;
Fellner answered 26/6, 2019 at 21:34 Comment(0)
P
0
StreamReader errorreader;
string InterviewID = txtToolsInterviewID.Text;

Process ffmpeg = new Process();

ffmpeg.StartInfo.UseShellExecute = false;
ffmpeg.StartInfo.ErrorDialog = false;
ffmpeg.StartInfo.RedirectStandardError = true;

ffmpeg.StartInfo.FileName = Server.MapPath("ffmpeg.exe");
ffmpeg.StartInfo.Arguments = "-i " + Server.MapPath("videos") + "\\226.flv";


ffmpeg.Start();

errorreader = ffmpeg.StandardError;

ffmpeg.WaitForExit();

string result = errorreader.ReadToEnd();

string duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00.00").Length);
Peterec answered 19/9, 2016 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.