Search code examples
c#naudio

how to get PCM data from stereo channel mp3 using Naudio in C#


I am new to Naudio and using it to get PCM data from Mp3 files, this is my code to take PCM from mono-channel file, but don't know how to do it with stereo channel file

code:

Mp3FileReader file = new Mp3FileReader(op.FileName);
int _Bytes = (int)file.Length;
byte[] Buffer = new byte[_Bytes];
file.Read(Buffer, 0, (int)_Bytes);
for (int i = 0; i < Buffer.Length - 2; i += 2)
{
  byte[] Sample_Byte = new byte[2];
  Sample_Byte[0] = Buffer[i + 1];
  Sample_Byte[1] = Buffer[i + 2];
  Int16 _ConvertedSample = BitConverter.ToInt16(Sample_Byte, 0);
}

How can I get PCM from stereo channel Mp3 file?


Solution

  • In a stereo file, the samples are interleaved: one left channel sample followed by one right channel etc. So in your loop you could go through four bytes at a time to read out the samples.

    Also there are some bugs in your code. You should use return value of Read, not the size of the buffer, and you have an off by one error in the code to access the samples. Also, no need to copy into a temporary buffer.

    Something like this should work for you:

    var file = new Mp3FileReader(fileName);
    int _Bytes = (int)file.Length;
    byte[] Buffer = new byte[_Bytes];
    
    int read = file.Read(Buffer, 0, (int)_Bytes);
    for (int i = 0; i < read; i += 4)
    {
        Int16 leftSample = BitConverter.ToInt16(Buffer, i);
        Int16 rightSample = BitConverter.ToInt16(Buffer, i + 2);
    }