簡體   English   中英

使用 naudio 獲取 1 秒音頻文件的分貝

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

我想使用 naudio 計算任何 .wav 文件的 1 秒分貝。 這是我的代碼:

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);

這一行:

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

返回 0。我做錯了什么?

我以另一種方式解決了這個任務。 這是一段代碼,可能對其他人有幫助:

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