NAudio WAV文件频率到分贝

时间:2015-11-24 15:28:53

标签: c# wav naudio frequency-analysis

我使用NAudio生成WAV文件。 Wav文件包含环境噪声(通过麦克风检测和记录)。 我需要处理此文件以显示针对不同频段的平均响度(dB)。 我读了很多关于1:3倍频带分析,其中频率窗口是31,62,125,250,500Hz等等。我们可以对每个窗口产生平均响度。 这正是我想要做的,但如何实现这一点似乎令人困惑。 到目前为止我所做的是(使用NAudio教程)读取WAV文件并进行处理。这是代码:

private void RenderFile()
{
    using (WaveFileReader reader = new WaveFileReader(this.voiceRecorderState.ActiveFile))
    {
        this.samplesPerSecond = reader.WaveFormat.SampleRate;
        SampleAggregator.NotificationCount = reader.WaveFormat.SampleRate/10;
        //Sample rate is 44100

        byte[] buffer = new byte[1024];
        WaveBuffer waveBuffer = new WaveBuffer(buffer);
        waveBuffer.ByteBufferCount = buffer.Length;
        int bytesRead;
        do
        {
            bytesRead = reader.Read(waveBuffer, 0, buffer.Length);
            int samples = bytesRead / 2;

            double sum = 0;
            for (int sample = 0; sample < samples; sample++)
            {
                if (bytesRead > 0)
                {
                    sampleAggregator.Add(waveBuffer.ShortBuffer[sample] / 32768f);
                    double sample1 = waveBuffer.ShortBuffer[sample] / 32768.0;
                    sum += (sample1 * sample1);

                }
            }
            double rms = Math.Sqrt(sum / (SampleAggregator.NotificationCount));
            double decibel = (double)(20 * Math.Log10(rms));
            if (calculatedBCount == 0)
            {
                dBList.Add(decibel);
                //  System.Diagnostics.Debug.WriteLine(decibel.ToString() + " in dB");
            }
        } while (bytesRead > 0);
        int totalSamples = (int)reader.Length / 2;
        TotalWaveFormSamples = totalSamples / sampleAggregator.NotificationCount;
        calculatedBCount++;
        SelectAll();

        //System.Diagnostics.Debug.WriteLine("Average Noise: " + avg.ToString() + " dB");
    }
    audioPlayer.LoadFile(this.voiceRecorderState.ActiveFile);
}


public int Read(byte[] buffer, int offset, int count)
{
    if (waveBuffer == null || waveBuffer.MaxSize < count)
    {
        waveBuffer = new WaveBuffer(count);
    }

    int bytesRead = source.Read(waveBuffer, 0, count);

    if (bytesRead > 0) bytesRead = count;

    int frames = bytesRead / sizeof(float); // MRH: was count
    float pitch = pitchDetector.DetectPitch(waveBuffer.FloatBuffer, frames);
    PitchList.Add(pitch);
    return frames * 4;
}

使用5秒WAV文件,从以上两种方法中,我得到一个Pitches和Decibels列表 分贝列表包含484个值,如:

-56.19945639
-55.13139952
-55.06947441
-56.70789076
-57.24140093
-55.98546603
-55.67407176
-55.53060998
-55.98480268
-54.85796943
-57.00735818
-55.64980974
-57.07235475

PitchList包含62个值,包括:

75.36621
247.631836
129.199219
75.36621
96.8994141
96.8994141
86.13281
75.36621
129.199219
107.666016

如何使用这些结果来识别31Hz,62Hz,125Hz,250Hz等的平均响度。

我做错了什么或者一切都错了,也许?

1 个答案:

答案 0 :(得分:0)

如果我错了,请纠正我但是......我担心你不能将HZ转换为DB,因为它们之间没有关系。  Hz是频率的度量,Db是幅度的度量,类似于千克到米。