您可以在 C# 应用程序中使用 FFmpeg 工具从视频文件中获取元数据信息,包括宽度和高度信息。不了解您的应用程序工作流程,我无法建议您何时应该阅读元数据信息。但一种可能的情况是这样的。
- 用户从磁盘中选择一堆视频文件,告诉您应用程序将它们加载到播放列表中进行播放。
- 在显示加载动画时,您通过 FFmpeg 工具运行每个视频以获取元数据信息,您可以将这些信息与文件名一起存储在内存或数据库中。
- 完成第 2 步后,用户可以看到播放列表中的视频。
- 当用户选择要播放的视频时,您会加载相应的宽度和高度信息,并在您的应用程序中设置媒体播放器控件的属性。
- 当用户移动到不同的视频时,您重复第 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 文件。