代码:
public class Decibelmeter { public event EventHandler Update = null; private bool _isStart = false; private int _decibelValue = 0; private byte[] _buffer = null; public bool IsStart { get { return _isStart; } } public int DecibelValue { get { return _decibelValue; } } public Decibelmeter() { Microphone.Default.BufferDuration = TimeSpan.FromSeconds(0.1d); int sampleSizeInBytes = Microphone.Default.GetSampleSizeInBytes(Microphone.Default.BufferDuration); this._buffer = new byte[sampleSizeInBytes]; CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering); FrameworkDispatcher.Update(); } void CompositionTarget_Rendering(object sender, EventArgs e) { FrameworkDispatcher.Update(); } public void Start() { Microphone.Default.BufferReady += new EventHandler<EventArgs>(Default_BufferReady); Microphone.Default.Start(); } public void Stop() { Microphone.Default.BufferReady -= new EventHandler<EventArgs>(Default_BufferReady); Microphone.Default.Stop(); } void Default_BufferReady(object sender, EventArgs e) { int data = Microphone.Default.GetData(this._buffer); if (data == 0) { return; } int averageVolume = this.GetAverageVolume(data); this._decibelValue = (int)((long)averageVolume / 200L); this.OnUpdate(EventArgs.Empty); } private int GetAverageVolume(int data) { long number = 0L; for (int i = 0; i < data; i += 2) { int number2 = Math.Abs((int)BitConverter.ToInt16(this._buffer, i)); number += (long)number2; } return (int)(number / (long)(data / 2)); } protected virtual void OnUpdate(EventArgs e) { if (this.Update != null) { this.Update(this, e); } } }
使用:
// 类全局变量 private Decibelmeter _decibelmeter = null; // 初始化Decibelmeter this._decibelmeter = new Decibelmeter(); this._decibelmeter.Update += new EventHandler(_decibelmeter_Update); this._decibelmeter.Start(); // Decibelmeter 更新 void _decibelmeter_Update(object sender, EventArgs e) { this.Dispatcher.BeginInvoke(new Action(() => { // 这里得到的value就是话筒录音的大小量 var value = this._decibelmeter.DecibelValue; })); }
非常感谢~!