GDIWindows VistaWindows 2003Visual Studio 2008Windows 2000Windows XP.NET 2.0C# 2.0中级开发Visual StudioWindows.NETC#
C# 中的声音激活录音机带频谱图






4.92/5 (51投票s)
音频事件处理和可视化显示

引言
这个项目演示了瀑布式频谱图的实现以及使用统计数据来触发近乎实时事件的方法。这段代码是对我之前提交的 (SoundViewer) 的扩展。这个演示使用了 Ianier Munoz 开发的 Wave
类。
Using the Code
音频由默认输入设备提供,通常是麦克风。当音频幅度超过期望的阈值时,会触发事件,该阈值可以在菜单栏的“选项”下设置。为了使其更有用,我添加了将流保存到磁盘的功能,从而实现了一个不错的声音激活录音机。
关注点
为了能够以足够快的速度绘制频谱图以实现近乎实时的操作,我需要使用不安全代码直接写入内存。
// lock image
PixelFormat format = canvas.PixelFormat;
BitmapData data =
canvas.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, format);
int stride = data.Stride;
int offset = stride - width * 4;
// draw image
try
{
unsafe
{
byte* pixel = (byte*)data.Scan0.ToPointer();
// for each column
for (int y = 0; y <= height; y++)
{
if (y < _fftLeftSpect.Count)
{
// for each row
for (int x = 0; x < width; x++, pixel += 4)
{
double amplitude = ((double[])_fftLeftSpect[_fftLeftSpect.Count - y - 1])
[(int)(((double)(_fftLeft.Length) / (double)(width)) * x)];
double color = GetColor(min, max, range, amplitude);
pixel[0] = (byte)0;
pixel[1] = (byte)color;
pixel[2] = (byte)0;
pixel[3] = (byte)255;
}
pixel += offset;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
// unlock image
canvas.UnlockBits(data);
我注意到,结果会因使用的硬件和相关驱动程序而大相径庭。
一些我想在有时间的时候进一步实验的事情
- 使用频域产生“运动”检测的等效功能
- 使用频谱图进行声音识别
- 提高性能/鲁棒性
历史
- 2008/01/16:创建