如何使用NAudio解压缩一帧?

时间:2018-02-20 07:47:22

标签: c# mp3 naudio pcm

我只是尝试从mp3文件中取出任何或第一帧,然后将其解压缩。

internal void Read3(string location) //take in file location
    {
        Mp3FileReader mp3 = new Mp3FileReader(location); //make a Mp3FileReader

        SECTIONA: //to jump back here when needed.

        byte[] _passedBuffer = Decompress(mp3.ReadNextFrame()); //passed the decompressed byte array here.
        int jump_size = mp3.WaveFormat.Channels *2; //just to get how many bytes to skip
        for (int i = 0; i < _passedBuffer.Length; i += jump_size)
        {
            short FinalSample = BitConverter.ToInt16(_passedBuffer, i);

            if (jump_size == 4) //converting the bytes to Int16,nothing special here.
            { 
               FinalSample = (short)(((BitConverter.ToInt16(_passedBuffer, i + 2)) + FinalSample) / 2); 
            }
            Console.Write(FinalSample+"|"); //and writing it down to Console.
        }
        Console.WriteLine("Frames are Written,continue to next frame?");
        if (Convert.ToChar(Console.Read()) == 'y') //asking to go on or not.
        { goto SECTIONA; }
    }


 private byte[] Decompress(Mp3Frame fm)
    {
        var buffer = new byte[16384 * 4]; //big enough buffer size
        WaveFormat wf = new Mp3WaveFormat(fm.SampleRate, fm.ChannelMode == ChannelMode.Mono ? 1 : 2, fm.FrameLength, fm.BitRate); //creating a new WaveFormat

        IMp3FrameDecompressor decompressor = new AcmMp3FrameDecompressor(wf); //passing in to AcmMp3FrameDecompressor.
        decompressor.DecompressFrame(fm, buffer, 0); //running the DecompressFrame method and then passing back the buffer.
        return buffer;

    }

现在,当我检查Frame的RawData时,Mp3FileReader正在正确读取帧。现在我尝试解压缩该帧,然后将其PCM数据转换为Int16,只有For循环,但每个Int16 FinalSample值返回0。 我知道只使用Mp3FileReader.Read(Buffer,Offset,Length)将完成工作,但所有框架都是如此:

  • 我如何只用一帧呢?
  • 我的代码出了什么问题,因为我的代码全部为零?
  • 我知道RawData没问题,所以Decompress方法一定有问题,如何为mp3文件设置解压缩器?

1 个答案:

答案 0 :(得分:1)

您可以使用AcmMp3FrameDecompressorDmoMp3FrameDecompressor解压缩各个MP3帧。

您需要检查Decompress的返回值,以查看返回的数据量。第一帧可能不返回任何内容。

你还应该创建一个单帧解压缩器并将其用于MP3文件中的所有帧,因为它在两次调用之间保持状态。