如何从mp4,wmv,flv,mov视频获取视频时长

时间:2012-04-17 12:05:58

标签: c# .net video mp4 duration

好的。其实我主要需要的是mp4格式。但是,如果有可能获得其他类型,那将是不错的。我只需要读取文件的持续时间。我怎么能用C#4.0做到这一点?

所以我需要的是这个视频就像:13 minutes 12 seconds

我也可以使用3个第三方的前任。就像他们将有关文件的信息保存到文本文件中一样。我可以解析该文本文件。

谢谢。

10 个答案:

答案 0 :(得分:12)

您也可以使用Windows媒体播放器,但它不支持您请求的文件类型

using WMPLib;

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

答案 1 :(得分:11)

您可以通过DirectShow.NET包装器库使用DirectShow API MediaDet对象。有关代码示例,请参阅Getting length of videoget_StreamLength以秒为单位获取持续时间。这假设Windows安装了MPEG-4解复用器(需要第三方组件与Windows之前的7,我相信这同样适用于另一个answer by cezor,但是可以自由地重新分发组件)。

答案 2 :(得分:9)

关于Shell32的P / Invoke的

This answer提醒我Windows API Code Pack访问常见的Windows Vista / 7/2008 / 2008R2 API。

使用包含的示例中的PropertyEdit演示,可以非常轻松地找出Shell32 API以获取各种媒体文件属性,例如持续时间。

我假设同样的先决条件适用于安装正确的解复用器,但它非常简单,因为它只需要添加对Microsoft.WindowsAPICodePack.dllMicrosoft.WindowsAPICodePack.Shell.dll的引用以及以下代码:

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

其他东西

MPEG-4 / AAC音频媒体文件的一些常见属性:

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

如果您正在寻找可用的元数据,则可以轻松遍历所有属性:

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

答案 3 :(得分:5)

恕我直言,您可以使用MediaInfo,它可以为您提供有关媒体文件的大量信息 它有一个CLI,因此您可以从代码中使用它并获取所需的信息 您可以查看this link

答案 4 :(得分:3)

我认为您正在寻找FFMPEG - http://www.ffmpeg-csharp.com/

在这个问题中,您还可以阅读一些免费的替代方案 - Using FFmpeg in .net?

   FFMpeg.NET
   FFMpeg-Sharp
   FFLib.NET

您可以看到此链接,了解使用FFMPEG并查找持续时间的示例 - 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]));
                }
            }
       }

答案 5 :(得分:3)

FFMPEG项目有一个名为ffprobe的工具,可以为您提供有关多媒体文件的信息,并以精美的JSON格式输出信息。

this answer为例说明一下。

答案 6 :(得分:2)

同样使用Windows Media Player组件,我们可以获得视频的持续时间 以下代码段可以帮助你们:

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

并且不要忘记添加 wmp.dll 的引用   存在于 System32 文件夹中。

答案 7 :(得分:1)

我发现NReco.VideoInfo library是最好的选择,而且远比上面的一些选择简单得多。给图书馆一个文件路径很简单,它会向外推出元数据:

var ffProbe = new FFProbe();
var videoInfo = ffProbe.GetMediaInfo(blob.Uri.AbsoluteUri);
return videoInfo.Duration.TotalMilliseconds;

答案 8 :(得分: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);

答案 9 :(得分:0)

我遇到了同样的问题,我们为ffprobe Alturos.VideoInfo构建了一个包装器。 您只需安装nuget软件包即可使用它。另外,ffprobe二进制文件也是必需的。

PM> install-package Alturos.VideoInfo

示例

var videoFilePath = "myVideo.mp4";

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

var duration = analyzeResult.VideoInfo.Format.Duration;