Search code examples
c#naudio

Quick normalizer for wav files not working as intended


I wrote a quick wave file normalizer in c# using naudio.

Currently it locks the thread and creates 1 KB files. sm is the highest peak of the file

using (WaveFileReader reader = new WaveFileReader(aktuellerPfad))
{
    using (WaveFileWriter writer = new WaveFileWriter("temp.wav", reader.WaveFormat))
    {
        byte[] bytesBuffer = new byte[reader.Length];
        int read = reader.Read(bytesBuffer, 0, bytesBuffer.Length);
        writer.WriteSample(read *32768/sm);
    }
}

Solution

  • You need to do mathematical operation in audio buffer to normalise the signal. The normalising steps would be:

    a. Read audio buffer as you are doing. (Although, I would prefer reading in chunks).

        byte[] bytesBuffer = new byte[reader.Length];
        reader.Read( bytesBuffer, 0, bytesBuffer.Length );
    

    b. Calculate multiplier value. There are different ways to calculate the value. I don't know how you are calculating but it looks the value is 32768/sm. I would denote multiplier as "mul".

    c. Now iterate through the buffer and multiply the value with the multiplier.

      for ( int i = 0; i < bytesBuffer.Length; i++ )
      {
          bytesBuffer[i] = bytesBuffer[i] * mul;
      }
    

    d. Finally, write samples to file.

    writer.WriteSamples( bytesBuffer, 0, bytesBuffer.Length );