C# 如何从 mp4、wmv、flv、mov 视频中获取视频时长

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10190906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:47:57  来源:igfitidea点击:

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

c#.netvideomp4duration

提问by MonsterMMORPG

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 ?

好吧。其实我主要需要mp4格式。但是,如果也可以获取其他类型,那就太好了。我只需要读取文件的持续时间。我怎样才能用 C# 4.0 做到这一点?

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

所以我需要的东西就像这个视频一样: 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.

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

Thank you.

谢谢你。

采纳答案by Roman R.

You can use DirectShow API MediaDetobject, through DirectShow.NET wrapper library. See Getting length of videofor code sample, get_StreamLengthgets 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).

您可以MediaDet通过 DirectShow.NET 包装库使用 DirectShow API对象。请参阅获取代码示例的视频长度get_StreamLength获取以秒为单位的持续时间。这假设 Windows 安装了 MPEG-4 解复用器(需要 Windows 7 之前的第三方组件,我相信这同样适用于cezor 的另一个答案,尽管可以免费重新分发组件)。

回答by Marco

IMHO you could use MediaInfowhich 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.

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

回答by Dor Cohen

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

我认为您正在寻找 FFMPEG - https://ffmpeg.org/

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

还有一些免费的替代方案,您可以在这个问题中阅读它们 -在 .net 中使用 FFmpeg?

   FFMpeg.NET
   FFMpeg-Sharp
   FFLib.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/

您可以查看此链接以获取使用 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]));
                }
            }
       }

回答by nickknissen

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

您也可以使用 windows 媒体播放器,尽管它不支持您请求的所有文件类型

using WMPLib;

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

回答by Paulo Fidalgo

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.

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

Take a look at this answerfor an example.

这个答案为例。

回答by nekno

This answerabout P/Invoke for Shell32 reminded me of the Windows API Code Packto access common Windows Vista/7/2008/2008R2 APIs.

这个关于 P/Invoke for Shell32 的回答让我想起了Windows API 代码包来访问常见的 Windows Vista/7/2008/2008R2 API。

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.

使用随附示例中的 PropertyEdit 演示很容易找出 Shell32 API 来获取各种媒体文件属性,例如持续时间。

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.dlland Microsoft.WindowsAPICodePack.Shell.dlland the following code:

我假设相同的先决条件适用于安装适当的解复用器,但它非常简单,因为它只需要添加对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);
}


Other stuff

其他的东西

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

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

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

回答by James Mundy

I found the NReco.VideoInfo libraryto 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:

我发现NReco.VideoInfo 库是最好的选择,而且比上面的一些要简单得多。这很简单,为库提供一个文件路径并输出元数据:

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

回答by Rish

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

还使用 Windows Media Player 组件,我们可以获得视频的持续时间。
以下代码片段可能对你们有所帮助:

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.dllwhich will be present in System32folder.

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

回答by Koby Douek

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

回答by Tino Hager

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

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

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;