NAudio分割mp3文件

时间:2011-05-23 07:47:30

标签: c# asp.net split mp3 naudio

我对音频或mp3的东西很新,正在寻找一种方法来在C#,asp.net中分割mp3文件。谷歌搜索了3天没有太大的帮助,我希望有人能指出我正确的方向。

我可以使用NAudio来实现这一目标吗?有没有示例代码?提前谢谢。

4 个答案:

答案 0 :(得分:12)

MP3文件由一系列MP3帧组成(通常在开头和结尾都加上ID3标签)。分割MP3文件最干净的方法是将一定数量的帧复制到一个新文件中(如果这很重要,也可以选择带上ID3标签)。

NAudio的MP3FileReader课程采用ReadNextFrame方法。这将返回一个MP3Frame类,其中包含原始数据作为RawData属性中的字节数组。它还包含SampleCount属性,您可以使用它来准确测量每个MP3帧的持续时间。

答案 1 :(得分:10)

我在c#中分割mp3文件的最终解决方案是使用NAudio。这是一个示例脚本,希望它可以帮助社区中的某个人:

string strMP3Folder = "<YOUR FOLDER PATH>";
string strMP3SourceFilename = "<YOUR SOURCE MP3 FILENAMe>";
string strMP3OutputFilename = "<YOUR OUTPUT MP3 FILENAME>";

using (Mp3FileReader reader = new Mp3FileReader(strMP3Folder + strMP3SourceFilename))
{
    int count = 1;
    Mp3Frame mp3Frame = reader.ReadNextFrame();
    System.IO.FileStream _fs = new System.IO.FileStream(strMP3Folder + strMP3OutputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);

    while (mp3Frame != null)
    {
        if (count > 500) //retrieve a sample of 500 frames
            return;

        _fs.Write(mp3Frame.RawData, 0, mp3Frame.RawData.Length);
        count = count + 1;
        mp3Frame = reader.ReadNextFrame();
     }

     _fs.Close();
}

感谢Mark Heath的建议。

所需的命名空间是NAudio.Wave。

答案 2 :(得分:5)

以前的答案帮助我开始了。 NAudio是要走的路。

对于我的PodcastTool我需要以2分钟的间隔分割播客,以便更快地寻找特定的地方。

以下是每N秒拆分一次mp3的代码:

    var mp3Path = @"C:\Users\ronnie\Desktop\mp3\dotnetrocks_0717_alan_dahl_imagethink.mp3";
    int splitLength = 120; // seconds

    var mp3Dir = Path.GetDirectoryName(mp3Path);
    var mp3File = Path.GetFileName(mp3Path);
    var splitDir = Path.Combine(mp3Dir,Path.GetFileNameWithoutExtension(mp3Path));
    Directory.CreateDirectory(splitDir);

    int splitI = 0;
    int secsOffset = 0;

    using (var reader = new Mp3FileReader(mp3Path))
    {   
        FileStream writer = null;       
        Action createWriter = new Action(() => {
            writer = File.Create(Path.Combine(splitDir,Path.ChangeExtension(mp3File,(++splitI).ToString("D4") + ".mp3")));
        });

        Mp3Frame frame;
        while ((frame = reader.ReadNextFrame()) != null)
        {           
            if (writer == null) createWriter();

            if ((int)reader.CurrentTime.TotalSeconds - secsOffset >= splitLength)
            {   
                // time for a new file
                writer.Dispose();
                createWriter();
                secsOffset = (int)reader.CurrentTime.TotalSeconds;              
            }

            writer.Write(frame.RawData, 0, frame.RawData.Length);
        }

        if(writer != null) writer.Dispose();
    }

答案 3 :(得分:2)

这些会有所帮助Alvas Audio(商业)和ffmpeg