Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

audio - How to retrieve duration of MP3 in .NET?

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.

Any libraries I should use? Or is it possible using only the .NET framework?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 method: not all files have id3 tags, and if they have it, they might not have duration field set in it.

Estimating by reading one frame * file size: not gonna work for VBR files.

Xing header: not all files have it.

Decoding and determining it via PCM size: I have 3+ GB file, I'm not going to wait until it decodes.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...