Reputation: 55
How can i convert stereo pcm samples to mono samples using naudio?
or converting an stereo mp3 file to mono raw samples!
i try this befor :
for (int u = 0; u < output.Length; u+=4)
{
byte[] Lbuffer = new byte[2];
byte[] Rbuffer = new byte[2];
Lbuffer[0] = output[u + 0];
Lbuffer[1] = output[u + 1];
Rbuffer[0] = output[u + 2];
Rbuffer[1] = output[u + 3];
Int16 leftSample = BitConverter.ToInt16(Lbuffer, 0);
Int16 rightSample = BitConverter.ToInt16(Rbuffer, 0);
Int16 mixedMono = (Int16)(0.5f * (float)leftSample + (float)rightSample);
Byte[] mixedMonoBytes = BitConverter.GetBytes(mixedMono);
mono[counter] = mixedMonoBytes[0];
mono[counter+1] = mixedMonoBytes[1];
//mono[counter] = Convert.ToByte((Convert.ToInt16(buffer[0]) + Convert.ToInt16(buffer[2]))/2);
//mono[counter+1] = Convert.ToByte((Convert.ToInt16(buffer[0]) + Convert.ToInt16(buffer[2]))/2);
counter += 2;
}
but it does not work currently! it result has noises! output is an array that contains raw samples!
Upvotes: 2
Views: 5785
Reputation: 1474
As @daniel-s pointed out, to convert PCM samples from stereo (2 channels) to mono (1 channel), you can simply take the average of the two channels: for every sample, take the value from the left channel, add the value from the right channel, and divide by 2. Use saturation arithmetic to avoid overflows.
To convert an MP3 file to raw (PCM) samples, you need to run the MP3 file through a file parser and MP3 bitstream decoder. There are many libraries and applications out there to do this; for example, see FFmpeg.
[Edit] I forgot to mention, more importantly, NAudio supports decoding MP3 files through either ACM or DMO codec; see NAudio - MP3 for examples.
Upvotes: 3