Search code examples
c#wavnaudio

Converting 16 bit to 32-nit floating point


I'm currently trying to convert a 16-bit sample to a 32-bit floating point. However, I encountered a problem where my audio time of 32-bit floating point file was cut in half. (For example, my input is a four-second 16-bit PCM WAV, and my output becomes a two-second IEEE float WAV.) Here is the code.

using (WaveFileReader reader = new WaveFileReader(file.wav))
{
    IWaveProvider stream32 = new Wave16ToFloatProvider(reader);

    using (WaveFileWriter converted = new WaveFileWriter(temp.wav))
    {
        // Buffer length needs to be a power of 2 for FFT to work nicely.
        // However, make the buffer too long and pitches aren't detected fast enough.
        // Successful buffer sizes: 8192, 4096, 2048, 1024 (some
        // pitch detection algorithms need at least 2048).
        byte[] buffer = new byte[8192];
        int bytesRead;
        do
        {
            bytesRead = stream32.Read(buffer, 0, buffer.Length);
            converted.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0 && converted.Length < reader.Length);
    }
}

Solution

  • The exit condition:

    } while (bytesRead != 0 && converted.Length < reader.Length);
    

    looks suspect; it sounds like you are expanding the data, so we should expected converted.Length to be more than reader.Length at the end - so my guess is that this exit condition is causing it to exit prematurely.