0

我有一个 C# 应用程序,它使用 Winforms 中的 Windows Media Player 控件 (WMPLib) 显示视频。

我可以正确显示视频,但我必须手动插入父控件的宽度和高度,这样视频看起来才不会失真。我的用例已经发展到我不再事先知道视频尺寸是多少,因此我需要找到一种方法来获取视频的实际宽度和高度。

我一直在研究是否可以在将视频加载到要播放的播放列表时执行此操作,然后将这些值传递给父控件的 Width 和 Height 参数,但我想不到...

这甚至可能吗?还是只有在播放视频时才能获得该信息?我应该从这里去哪里?

谢谢!

4

1 回答 1

0

您可以在 C# 应用程序中使用 FFmpeg 工具从视频文件中获取元数据信息,包括宽度和高度信息。不了解您的应用程序工作流程,我无法建议您何时应该阅读元数据信息。但一种可能的情况是这样的。

  1. 用户从磁盘中选择一堆视频文件,告诉您应用程序将它们加载到播放列表中进行播放。
  2. 在显示加载动画时,您通过 FFmpeg 工具运行每个视频以获取元数据信息,您可以将这些信息与文件名一起存储在内存或数据库中。
  3. 完成第 2 步后,用户可以看到播放列表中的视频。
  4. 当用户选择要播放的视频时,您会加载相应的宽度和高度信息,并在您的应用程序中设置媒体播放器控件的属性。
  5. 当用户移动到不同的视频时,您重复第 4 步。

现在有很多 FFmpeg 的 C# 库。有的付费,有的免费。但我一直在使用一些前段时间从同事那里获得的代码。它不仅仅是获取元数据。它还可以将视频转换为 FLV 格式。我在这里上传到 github 。提取元数据的实际方法如下所示。

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

        //get audio bit rate
        re = new Regex("[B|b]itrate:.((\\d|:)*)");
        m = re.Match(input.RawInfo);
        double kb = 0.0;
        if (m.Success)
        {
            Double.TryParse(m.Groups[1].Value, out kb);
        }
        input.BitRate = kb;

        //get the audio format
        re = new Regex("[A|a]udio:.*");
        m = re.Match(input.RawInfo);
        if (m.Success)
        {
            input.AudioFormat = m.Value;
        }

        //get the video format
        re = new Regex("[V|v]ideo:.*");
        m = re.Match(input.RawInfo);
        if (m.Success)
        {
            input.VideoFormat = m.Value;
        }

        //get the video format
        re = new Regex("(\\d{2,3})x(\\d{2,3})");
        m = re.Match(input.RawInfo);
        if (m.Success)
        {
            int width = 0; int height = 0;
            int.TryParse(m.Groups[1].Value, out width);
            int.TryParse(m.Groups[2].Value, out height);
            input.Width = width;
            input.Height = height;
        }
        input.infoGathered = true;
    }

代码可能会使用一些优化,包括 IDisposable 和 dispose 模式的实现。但是,这对您来说应该是一个很好的起点。您还需要从此处下载 FFmpeg 可执行文件,并使用 FFmpeg 可执行文件的路径更新您的 App.config 文件。

于 2014-04-28T18:28:31.803 回答