This project has moved. For the latest updates, please go here.

NAudio - RMS amplitude of a wav file.

Nov 1, 2016 at 6:12 PM
Edited Nov 2, 2016 at 11:36 PM
Hello,

I want to find RMS amplitude in db of a wav file (16 bit PCM) using NAudio but my values seem to be way off. Can someone help me how to do this. The code I have is

static void CheckAmplitude(string srcPath)
    {

        using (WaveFileReader audiowave = new NAudio.Wave.WaveFileReader(srcPath))
        {
            byte[] fileBuffer = new byte[audiowave.Length];
            int read = audiowave.Read(fileBuffer, 0, fileBuffer.Length);
            short[] sampleBuffer = new short[read / 2];
            Buffer.BlockCopy(fileBuffer, 0, sampleBuffer, 0, read);
            double rms = rootMeanSquare(sampleBuffer);
        }
}
   private static double rootMeanSquare(short[] x)
    {
        double sum = 0;
        for (int i = 0; i < x.Length; i++)
        {
            double Tmp;
           Tmp = x[i] / 32768f;
            sum += (Tmp *Tmp);

        }
        return Math.Sqrt(sum / x.Length);
    }
Nov 5, 2016 at 12:40 AM
Reading from a samplePovider is easier than converting the data yourself... use extension WaveFileReader.ToSampleProvider()

The formula in the function itself seems correct.