page contents

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

本文讲述了C#使用naudio获取1秒音频文件的分贝!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

attachments-2022-09-AMtaykfM63365148d7743.png本文讲述了C#使用naudio获取1秒音频文件的分贝!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

我想使用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.我做错了什么?

1 个答案:

答案 0 :(得分:4)

我以另一种方式解决了这个问题。这是一段代码,可以帮助其他人:

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

}

更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2022-09-30 10:16
  • 阅读 ( 496 )
  • 分类:C/C++开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
轩辕小不懂
轩辕小不懂

2403 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. Pack 1131 文章
  3. 小柒 1046 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章