简体   繁体   English

使用 naudio 获取 1 秒音频文件的分贝

[英]Get decibels of 1 second of audio file using naudio

I wanna to calculate decibels of 1 second of any .wav file using naudio.我想使用 naudio 计算任何 .wav 文件的 1 秒分贝。 This is my code:这是我的代码:

WaveFileReader reader = new WaveFileReader(@"C:\Users\Admin\Desktop\result.wav");
int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;            
//byte[] buffer = new byte[reader.Length];
//int read = reader.Read(buffer, 0, (int)reader.Length);
TimeSpan time = new TimeSpan(0, 0, 1);

int bytesPerSecond = (int)time.TotalMilliseconds * bytesPerMillisecond;
byte[] oneSecondBuffer = new byte[bytesPerSecond];
int read = reader.Read(oneSecondBuffer, 0, bytesPerSecond);

short sample16Bit = BitConverter.ToInt16(oneSecondBuffer, 1);
double volume = Math.Abs(sample16Bit / 32768.0);
double decibels = 20 * Math.Log10(volume);

This line:这一行:

short sample16Bit = BitConverter.ToInt16(oneSecondBuffer, 1);

returns 0. What am I doing wrong?返回 0。我做错了什么?

I've resolved this task in another way.我以另一种方式解决了这个任务。 This is a piece of code, which may help other people:这是一段代码,可能对其他人有帮助:

var silenceDict = new Dictionary<int, bool>();
using (NAudio.Wave.AudioFileReader wave = new NAudio.Wave.AudioFileReader(filePath))
{
    var samplesPerSecond = wave.WaveFormat.SampleRate * wave.WaveFormat.Channels;
    var readBuffer = new float[samplesPerSecond];
    int samplesRead;
    int i = 1;
    do
    {
        samplesRead = wave.Read(readBuffer, 0, samplesPerSecond);
        if (samplesRead == 0) break;
        var max = readBuffer.Take(samplesRead).Max();

        if ((int)(max * 100) != 0)
            silenceDict.Add(i, false);
        else
            silenceDict.Add(i, true);

        i++;
    } while (samplesRead > 0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM