Get decibels per second of an audio file using
I want to calculate decibels per second of any .wav file using naudio. 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?
+3
source to share
1 answer
I solved this problem in a different way. This is a piece of code that might 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);
}
+3
source to share