Search code examples
c#audionaudiosampling

Read method returning twice the number of samples actually present


I have the following code to read the samples of an audio file into a byte array.

int signal_read = signal.Read(signal_sample, 0, signal_length);
MessageBox.Show(signal_read + "");

where signal is an object of WaveFileReaderclass.

MessageBox.Show always shows twice the actual number of samples got from the software Audacity.

Does read method not return the number of samples read from audio?


Solution

  • No, it returns the number of bytes read.

    So for a 16-bit PCM wav, it will give you twice the amount of samples. If it's a stereo 16-bit, you'll get four times as much.

    Instead of reading the bytes, you probably want to use the overload that fills a float[][] array. For example, for a single-channel audio:

    var array = new float[][] { new float[sampleCount] };
    
    var actualSamples = signal.Read(array, sampleCount);