如何在 .NET 中检索 MP3 的持续时间? [英] How to retrieve duration of MP3 in .NET?

查看:28
本文介绍了如何在 .NET 中检索 MP3 的持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个 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:不是所有文件都有.

Xing header: not all files have it.

通过 PCM 大小解码和确定它:我有 3 GB 以上的文件,我不会等到它解码.

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

我到处阅读,所有的东西都指向 NAudio.马克,感谢您的努力和干净的来源!但是,NAudio 主要建议的一种方法是使用 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 :)

Mark 建议我删除 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;
    }

这篇关于如何在 .NET 中检索 MP3 的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆