The easiest way to read 2-channel samples into an array from WaveStream

I struggled with this for quite some time, and I could not find a working solution.

I have a wav file (16 bit PCM: 44 kHz 2 channels) and I want to extract samples into two arrays for each of the two channels. As far as I know, a direct method for this does not exist in the NAudio library, so I tried to run the following code to read a few interlaced samples, but the buffer array remains empty (only a few zeros):

using (WaveFileReader pcm = new WaveFileReader(@"file.wav")) { byte[] buffer = new byte[10000]; using (WaveStream aligned = new BlockAlignReductionStream(pcm)) { aligned.Read(buffer, 0, 10000); } } 

Any help on this would be greatly appreciated.

+7
source share
1 answer

BlockAlignReductionStream not required. Here is one easy way to read from your buffer and into separate 16-bit left and right buffers.

 using (WaveFileReader pcm = new WaveFileReader(@"file.wav")) { int samplesDesired = 5000; byte[] buffer = new byte[samplesDesired * 4]; short[] left = new short[samplesDesired]; short[] right = new short[samplesDesired]; int bytesRead = pcm.Read(buffer, 0, 10000); int index = 0; for(int sample = 0; sample < bytesRead/4; sample++) { left[sample] = BitConverter.ToInt16(buffer, index); index += 2; right[sample] = BitConverter.ToInt16(buffer, index); index += 2; } } 
+4
source

All Articles