1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6 using System.IO;
7 using System.Windows.Forms;
8 using Microsoft.DirectX;
9 using Microsoft.DirectX.DirectSound;
10
11 namespace DQ
12 {
13 class SoundRecord
14 {
15 #region 成员数据
16 private Capture mCapDev = null; // 音频捕捉设备
17 private CaptureBuffer mRecBuffer = null; // 缓冲区对象
18 private WaveFormat mWavFormat; // 录音的格式
19
20 private int mNextCaptureOffset = 0; // 该次录音缓冲区的起始点
21 private int mSampleCount = 0; // 录制的样本数目
22 private int LockSize = 0;
23
24 private Notify mNotify = null; // 消息通知对象
25 public const int cNotifyNum = 16; // 通知的个数
26 private int mNotifySize = 0; // 每次通知大小
27 private int mBufferSize = 0; // 缓冲队列大小
28 private Thread mNotifyThread = null; // 处理缓冲区消息的线程
29 private AutoResetEvent mNotificationEvent = null; // 通知事件
30
31 private string mFileName = string.Empty; // 文件保存路径
32 private FileStream mWaveFile = null; // 文件流
33 private BinaryWriter mWriter = null; // 写文件
34 private static int[] SAMPLE_FORMAT_ARRAY = { 16, 2, 1 };
35 public int CurrentVolume;
36 byte[] CaptureData = null;
37 public List<int> VolumnList = new List<int>();
38 public int AverageVolumn;
39 #endregion
40 #region 对外操作函数
41 /// <summary>
42 /// 构造函数,设定录音设备,设定录音格式.
43 /// <summary>
44 public SoundRecord()
45 {
46 // 初始化音频捕捉设备
47 InitCaptureDevice();
48 // 设定录音格式
49 mWavFormat = CreateWaveFormat();
50 }
51
52 /// <summary>
53 /// 创建录音格式,此处使用16bit,16KHz,Mono的录音格式
54 /// <summary>
55 private WaveFormat CreateWaveFormat()
56 {
57 WaveFormat format = new WaveFormat();
58 format.FormatTag = WaveFormatTag.Pcm; // PCM
59 format.SamplesPerSecond = 16000; // 采样率:16KHz
60 format.BitsPerSample = 16; // 采样位数:16Bit
61 format.Channels = 1; // 声道:Mono
62 format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8)); // 单位采样点的字节数
63 format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;
64 return format;
65 // 按照以上采样规格,可知采样1秒钟的字节数为 16000*2=32000B 约为31K
66 }
67
68 /// <summary>
69 /// 设定录音结束后保存的文件,包括路径
70 /// </summary>
71 /// <param name="filename">保存wav文件的路径名</param>
72 public void SetFileName(string filename)
73 {
74 mFileName = filename;
75 }
76
77 /// <summary>
78 /// 开始录音
79 /// </summary>
80 public void RecStart()
81 {
82 // 创建录音文件
83 CreateSoundFile();
84 // 创建一个录音缓冲区,并开始录音
85 CreateCaptureBuffer();
86 // 建立通知消息,当缓冲区满的时候处理方法
87 InitNotifications();
88 mRecBuffer.Start(true);
89 }
90
91
92 /// <summary>
93 /// 停止录音
94 /// </summary>
95 public void RecStop()
96 {
97 mRecBuffer.Stop(); // 调用缓冲区的停止方法,停止采集声音
98 if (null != mNotificationEvent)
99 mNotificationEvent.Set(); //关闭通知
100 mNotifyThread.Abort(); //结束线程
101 RecordCapturedData(); // 将缓冲区最后一部分数据写入到文件中
102 // 写WAV文件尾
103 mWriter.Seek(4, SeekOrigin.Begin);
104 mWriter.Write((int)(mSampleCount + 36)); // 写文件长度
105 mWriter.Seek(40, SeekOrigin.Begin);
106 mWriter.Write(mSampleCount); // 写数据长度
107
108 mWriter.Close();
109 mWaveFile.Close();
110 mWriter = null;
111 mWaveFile = null;
112 }
113 #endregion
114 #region 对内操作函数
115 /// <summary>
116 /// 初始化录音设备,此处使用主录音设备.
117 /// </summary>
118 /// <returns>调用成功返回true,否则返回false</returns>
119 private bool InitCaptureDevice()
120 {
121 // 获取默认音频捕捉设备
122 CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚举音频捕捉设备
123 Guid deviceGuid = Guid.Empty;
124
125 if (devices.Count > 0)
126 deviceGuid = devices[0].DriverGuid;
127 else
128 {
129 MessageBox.Show("系统中没有音频捕捉设备");
130 return false;
131 }
132
133 // 用指定的捕捉设备创建Capture对象
134 try
135 {
136 mCapDev = new Capture(deviceGuid);
137 }
138 catch (DirectXException e)
139 {
140 MessageBox.Show(e.ToString());
141 return false;
142 }
143 return true;
144 }
145
146 /// <summary>
147 /// 创建录音使用的缓冲区
148 /// </summary>
149 private void CreateCaptureBuffer()
150 {
151 // 缓冲区的描述对象
152 CaptureBufferDescription bufferdescription = new CaptureBufferDescription();
153 if (null != mNotify)
154 {
155 mNotify.Dispose();
156 mNotify = null;
157 }
158 if (null != mRecBuffer)
159 {
160 mRecBuffer.Dispose();
161 mRecBuffer = null;
162 }
163 // 设定通知的大小,默认为1s钟
164 mNotifySize = (1024 > mWavFormat.AverageBytesPerSecond / 8) ? 1024 : (mWavFormat.AverageBytesPerSecond / 8);
165 mNotifySize -= mNotifySize % mWavFormat.BlockAlign;
166 // 设定缓冲区大小
167 mBufferSize = mNotifySize * cNotifyNum;
168 // 创建缓冲区描述
169 bufferdescription.BufferBytes = mBufferSize;
170 bufferdescription.Format = mWavFormat; // 录音格式
171 // 创建缓冲区
172 mRecBuffer = new CaptureBuffer(bufferdescription, mCapDev);
173 mNextCaptureOffset = 0;
174 }
175
176 /// <summary>
177 /// 初始化通知事件,将原缓冲区分成16个缓冲队列,在每个缓冲队列的结束点设定通知点.
178 /// </summary>
179 /// <returns>是否成功</returns>
180 private bool InitNotifications()
181 {
182 if (null == mRecBuffer)
183 {
184 MessageBox.Show("未创建录音缓冲区");
185 return false;
186 }
187 // 创建一个通知事件,当缓冲队列满了就激发该事件.
188 mNotificationEvent = new AutoResetEvent(false);
189 // 创建一个线程管理缓冲区事件
190 if (null == mNotifyThread)
191 {
192 mNotifyThread = new Thread(new ThreadStart(WaitThread));
193 mNotifyThread.Start();
194 }
195 // 设定通知的位置
196 BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1];
197 for (int i = 0; i < cNotifyNum; i++)
198 {
199 PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1;
200 PositionNotify[i].EventNotifyHandle = mNotificationEvent.SafeWaitHandle.DangerousGetHandle();
201 }
202 mNotify = new Notify(mRecBuffer);
203 mNotify.SetNotificationPositions(PositionNotify, cNotifyNum);
204 return true;
205 }
206
207 /// <summary>
208 /// 接收缓冲区满消息的处理线程
209 /// </summary>
210 private void WaitThread()
211 {
212 while (true)
213 {
214 // 等待缓冲区的通知消息
215 mNotificationEvent.WaitOne(Timeout.Infinite, true);
216 // 录制数据
217 RecordCapturedData();
218 }
219 }
220
221 /// <summary>
222 /// 将录制的数据写入wav文件
223 /// </summary>
224 private void RecordCapturedData()
225 {
226 int ReadPos = 0, CapturePos = 0;
227 mRecBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
228 LockSize = ReadPos - mNextCaptureOffset;
229 if (LockSize < 0) // 因为是循环的使用缓冲区,所以有一种情况下为负:当文以载读指针回到第一个通知点,而Ibuffeoffset还在最后一个通知处
230 LockSize += mBufferSize;
231 LockSize -= (LockSize % mNotifySize); // 对齐缓冲区边界,实际上由于开始设定完整,这个操作是多余的.
232 if (0 == LockSize)
233 return;
234
235 // 读取缓冲区内的数据
236 try
237 {
238 CaptureData = (byte[])mRecBuffer.Read(mNextCaptureOffset, typeof(byte), LockFlag.None, LockSize);
239 }
240 catch
241 {
242
243 }
244 #region 获取音量
245 try
246 {
247 int tempFrameDelay = 10;
248 int tempSampleDelay = 100;
249 Array samples = mRecBuffer.Read(mNextCaptureOffset, typeof(Int16), LockFlag.FromWriteCursor, SAMPLE_FORMAT_ARRAY);
250
251 int goal = 0;
252
253 for (int i = 0; i < 16; i++)
254 {
255 goal += (Int16)samples.GetValue(i, 0, 0);
256 }
257
258 goal = (int)Math.Abs(goal / 16);
259
260 double range = goal - CurrentVolume;
261
262 double exactValue = CurrentVolume;
263
264 double stepSize = range / tempSampleDelay * tempFrameDelay;
265 if (Math.Abs(stepSize) < .01)
266 {
267 stepSize = Math.Sign(range) * .01;
268 }
269 double absStepSize = Math.Abs(stepSize);
270
271 if ((CurrentVolume == goal))
272 {
273 //Thread.Sleep(tempSampleDelay);
274 }
275 else
276 {
277 do
278 {
279 if (CurrentVolume != goal)
280 {
281 if (absStepSize < Math.Abs(goal - CurrentVolume))
282 {
283 exactValue += stepSize;
284 CurrentVolume = (int)Math.Round(exactValue);
285 //Console.WriteLine("当前麦克风音量:"+CurrentVolume);
286 VolumnList.Add(CurrentVolume);
287 AverageVolumn = Convert.ToInt32(VolumnList.Average());
288 }
289 else
290 {
291 CurrentVolume = goal;
292 }
293 }
294 //Thread.Sleep(tempFrameDelay);
295 } while ((CurrentVolume != goal));
296 }
297 }
298 catch
299 {
300
301 }
302 #endregion
303 // 写入Wav文件
304 mWriter.Write(CaptureData, 0, CaptureData.Length);
305 // 更新已经录制的数据长度.
306 mSampleCount += CaptureData.Length;
307 // 移动录制数据的起始点,通知消息只负责指示产生消息的位置,并不记录上次录制的位置
308 mNextCaptureOffset += CaptureData.Length;
309 mNextCaptureOffset %= mBufferSize; // Circular buffer
310 }
311
312 /// <summary>
313 /// 创建保存的波形文件,并写入必要的文件头.
314 /// </summary>
315 private void CreateSoundFile()
316 {
317 // Open up the wave file for writing.
318 mWaveFile = new FileStream(mFileName, FileMode.Create);
319 mWriter = new BinaryWriter(mWaveFile);
320 /**************************************************************************
321 Here is where the file will be created. A
322 wave file is a RIFF file, which has chunks
323 of data that describe what the file contains.
324 A wave RIFF file is put together like this:
325 The 12 byte RIFF chunk is constructed like this:
326 Bytes 0 - 3 : 'R' 'I' 'F' 'F'
327 Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description.
328 (4 bytes for "WAVE" + 24 bytes for format chunk length +
329 8 bytes for data chunk description + actual sample data size.)
330 Bytes 8 - 11: 'W' 'A' 'V' 'E'
331 The 24 byte FORMAT chunk is constructed like this:
332 Bytes 0 - 3 : 'f' 'm' 't' ' '
333 Bytes 4 - 7 : The format chunk length. This is always 16.
334 Bytes 8 - 9 : File padding. Always 1.
335 Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo.
336 Bytes 12- 15: Sample rate.
337 Bytes 16- 19: Number of bytes per second.
338 Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or
339 16 bit mono, 4 for 16 bit stereo.
340 Bytes 22- 23: Number of bits per sample.
341 The DATA chunk is constructed like this:
342 Bytes 0 - 3 : 'd' 'a' 't' 'a'
343 Bytes 4 - 7 : Length of data, in bytes.
344 Bytes 8 -: Actual sample data.
345 ***************************************************************************/
346 // Set up file with RIFF chunk info.
347 char[] ChunkRiff = { 'R', 'I', 'F', 'F' };
348 char[] ChunkType = { 'W', 'A', 'V', 'E' };
349 char[] ChunkFmt = { 'f', 'm', 't', ' ' };
350 char[] ChunkData = { 'd', 'a', 't', 'a' };
351
352 short shPad = 1; // File padding
353 int nFormatChunkLength = 0x10; // Format chunk length.
354 int nLength = 0; // File length, minus first 8 bytes of RIFF description. This will be filled in later.
355 short shBytesPerSample = 0; // Bytes per sample.
356
357 // 一个样本点的字节数目
358 if (8 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels)
359 shBytesPerSample = 1;
360 else if ((8 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels) || (16 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels))
361 shBytesPerSample = 2;
362 else if (16 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels)
363 shBytesPerSample = 4;
364
365 // RIFF 块
366 mWriter.Write(ChunkRiff);
367 mWriter.Write(nLength);
368 mWriter.Write(ChunkType);
369
370 // WAVE块
371 mWriter.Write(ChunkFmt);
372 mWriter.Write(nFormatChunkLength);
373 mWriter.Write(shPad);
374 mWriter.Write(mWavFormat.Channels);
375 mWriter.Write(mWavFormat.SamplesPerSecond);
376 mWriter.Write(mWavFormat.AverageBytesPerSecond);
377 mWriter.Write(shBytesPerSample);
378 mWriter.Write(mWavFormat.BitsPerSample);
379
380 // 数据块
381 mWriter.Write(ChunkData);
382 mWriter.Write((int)0); // The sample length will be written in later.
383 }
384 #endregion
385 }
386 }