音频中的电平可以反映出声音的响度,用一些设备进行的时候如果声音过大会出现爆音现象(老款go pro)大家俗称的爆音实际就是输入的电平过大了。
NAudio 是一个挺好用的音频库 基本上能处理涉及音频的全部操作了, 具体可以自行了解。此次主要尝试使用它来进行电平图的绘制,可以在录音时给人一定的参考从而预防爆音。
using NAudio.CoreAudioApi;
using NAudio.Wave;
using System.Diagnostics;
using System.Windows.Forms;
using NAudio.Wave;
namespace audioTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 初始化NAudio WaveIn事件
waveIn = new WaveInEvent();
waveIn.DataAvailable += WaveIn_DataAvailable;
waveIn.WaveFormat = new WaveFormat(44100, 1); // 采样率和通道数根据你的音频文件设置
// 初始化绘图相关对象
levelMeterBitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.Image = levelMeterBitmap;
levelMeterGraphics = Graphics.FromImage(levelMeterBitmap);
levelMeterPen = new Pen(Color.Green);
}
private WaveInEvent waveIn;
private Bitmap levelMeterBitmap;
private Graphics levelMeterGraphics;
private Pen levelMeterPen;
private void Form1_Load(object sender, EventArgs e)
{
waveIn.StartRecording();
}
private void WaveIn_DataAvailable(object sender, WaveInEventArgs e)
{
float[] buffer = new float[e.BytesRecorded / 4]; // 4 bytes per float
// 将字节数组转换为浮点数数组
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = BitConverter.ToSingle(e.Buffer, i * 4);
}
// 计算音频电平(振幅)并绘制
float amplitude = Math.Abs(buffer.Max()); // 获取最大振幅
// 清空绘图区域
levelMeterGraphics.Clear(Color.Black);
// 绘制电平图
int barWidth = (int)(amplitude * pictureBox1.Width);
levelMeterGraphics.FillRectangle(levelMeterPen.Brush, 0, 0, barWidth, pictureBox1.Height);
// 刷新PictureBox以显示电平图
pictureBox1.Invalidate();
}
}
}
NAudio确实方便哈