Getting MP4 File Duration with DirectShow

左心房为你撑大大i 提交于 2019-12-01 12:34:56

问题


I need to get the duration of an mp4 file, preferably as a double in seconds. I was using DirectShow (see code below), but it keeps throwing a particularly unhelpful error. I'm wondering if someone has an easy solution to this. (Seriously, who knew that getting that information would be so difficult)

public static void getDuration(string moviePath)
    {
        FilgraphManager m_objFilterGraph = null;
        m_objFilterGraph = new FilgraphManager();
        m_objFilterGraph.RenderFile(moviePath);

        IMediaPosition m_objMediaPosition = null;
        m_objMediaPosition = m_objFilterGraph as IMediaPosition;

        Console.WriteLine(m_objMediaPosition.Duration);
    }

Whenever I run this code, I get the error: "Exception from HRESULT: 0x80040265"

I also tried using this: Getting length of video but it doesn't work either because I don't think that it works on MP4 files.

Seriously, I feel like there has to be a much easier way to do this.

Note: I would prefer to avoid using exe's like ffmpeg and then parsing the output to get the information.


回答1:


You are approaching the problem correctly. You need to build a good pipeline starting from source .MP4 file and up to video and audio renderers. Then IMediaPosition.Duration will get you what you want. Currently you are getting VFW_E_UNSUPPORTED_STREAM because you cannot build the pipeline.

Note that there is no good support for MPEG-4 in DirectShow in clean Windows, you need a third party parser installed to add missing blocks. This is the likely cause of your problem. There are good Free DirectShow Mpeg-4 Filters available to fill this gap.

The code sample under the link Getting length of video is basically valid too, however it uses deprecated component which in additional make additional assumptions onto the media file in question. Provided that there is support for .MP4 in the system, IMediaPosition.Duration is to give you what you look for.




回答2:


You can use get_Duration() from IMediaPosition interface.

This return a double value with the video duration in seconds.

    Double Lenght;

    m_FilterGraph = new FilterGraph()

//Configure the FilterGraph()

    m_mediaPosition = m_FilterGraph as IMediaPosition;
    m_mediaPosition.get_Duration(out Length);



回答3:


Using Windows Media Player Component also, we can get the duration of the video.
I hope that 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.



来源:https://stackoverflow.com/questions/11346136/getting-mp4-file-duration-with-directshow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!