Search code examples
c#audiowavnaudiovoice

NAudio : Read Wav File As Double Array


Assuming my WAV file contains 16 bit PCM, How can I read wav file as double array:

 using (WaveFileReader reader = new WaveFileReader("myfile.wav"))
{
    Assert.AreEqual(16, reader.WaveFormat.BitsPerSample, "Only works with 16 bit audio");
    byte[] bytesBuffer = new byte[reader.Length];
    int read = reader.Read(bytesBuffer, 0, buffer.Length);
    // HOW TO GET AS double ARRAY
}

Solution

  • 16-bit PCM is an signed-integer encoding. Presuming you want doubles between 0 and 1, you simply read each sample as an 16-bit signed integer, and then divide by (double)32768.0;

    var floatSamples = new double[read/2];
    for(int sampleIndex = 0; sampleIndex < read/2; sampleIndex++) {
       var intSampleValue = BitConverter.ToInt16(bytesBuffer, sampleIndex*2);
       floatSamples[sampleIndex] = intSampleValue/32768.0;
    }
    

    Note that stereo channels are interleaved (left sample, right sample, left sample, right sample).

    There's some good info on the format here: http://blog.bjornroche.com/2013/05/the-abcs-of-pcm-uncompressed-digital.html