我有建立一个WPF应用程序,用户可以拖放MP3文件到列表框。我需要一种方法来计算播放列表的总时间。
I have build a WPF application where users can drag and drop MP3 files onto a listbox. I need a way to calculate the total duration of the playlist.
我应该使用任何库?或者只使用了.NET框架是这可能吗?
Any libraries I should use? Or is it possible using only the .NET framework?
经过大量的理论,我发现了一种正确和无可争议地计算一个mp3文件的时间。
After lots of theorizing, I found a way to correctly and indisputably calculate a duration of an mp3 file.
首先,我要再次重申,为什么标准方法上面将无法工作:
Let me first re-iterate why standard methods above won't work:
ID3方法:不是所有的文件都ID3标签,如果他们有,他们可能没有时间字段将其设置
ID3 method: not all files have id3 tags, and if they have it, they might not have duration field set in it.
估计读一帧*文件大小:对VBR文件不是要去工作
Estimating by reading one frame * file size: not gonna work for VBR files.
兴头:不是所有的文件都有它
Xing header: not all files have it.
解码,并通过PCM大小决定的:我有3+ GB的文件,我不会等到它去codeS
Decoding and determining it via PCM size: I have 3+ GB file, I'm not going to wait until it decodes.
我读无处不在,所有的东西导致n音讯。马克,感谢您的好功夫的清洁能源!然而,一个方法,大多与n音讯建议是阅读使用Mp3FileReader一个文件,获取所有帧。问题:Mp3FileReader在开始创建TOC并且需要永远,即使只有一天小档案:)
I read everywhere and all things lead to NAudio. Mark, THANKS for the good effort and clean source! However, a method that is mostly suggested with NAudio is to read a file using Mp3FileReader and get all frames. Problem: Mp3FileReader creates a TOC at the start and that takes forever, even for small files of only ONE day :)
马克建议我删除TOC创建,因为源代码是可用的,并且在做的过程中,我发现很多简单的方法。这里是;是不言自明的:
Mark suggested that I remove TOC creation, since source is available, and while doing it, I found much simpler method. Here it is; is speaks for itself:
double GetMediaDuration(string MediaFilename)
{
double duration = 0.0;
using (FileStream fs = File.OpenRead(MediaFilename))
{
Mp3Frame frame = Mp3Frame.LoadFromStream(fs);
if (frame != null)
{
_sampleFrequency = (uint)frame.SampleRate;
}
while (frame != null)
{
if (frame.ChannelMode == ChannelMode.Mono)
{
duration += (double)frame.SampleCount * 2.0 / (double)frame.SampleRate;
}
else
{
duration += (double)frame.SampleCount * 4.0 / (double)frame.SampleRate;
}
frame = Mp3Frame.LoadFromStream(fs);
}
}
return duration;
}