8

I've been struggling with this for quite some time now and I couldn't find a working solution.

I have a wav file (16 bit PCM: 44kHz 2 channels) and I want to extract samples into two arrays for each of the two channels. As far as I know the direct method for this does not exist in NAudio library, so I tried to run the following code to read a few of interlaced samples but the buffer array stays empty (just a bunch of 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 will be much appreciated.

yamen
  • 15,390
  • 3
  • 42
  • 52
Matic Jurglič
  • 831
  • 9
  • 26
  • Have you seen this: http://mark-dot-net.blogspot.com.au/2012/01/handling-multi-channel-audio-in-naudio.html – yamen May 03 '12 at 12:42

1 Answers1

4

BlockAlignReductionStream is unnecessary. Here's one simple way to read out of your buffer and into separate 16 bit left and right sample 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;
    }
}
Mark Heath
  • 48,273
  • 29
  • 137
  • 194