一.声卡录音的基本原理
为了实现一个录音的基本过程,至少需要以下对象的支持:
1. 录音设备,对我们的PC设备就是声卡。这个录音设备可以进行的操作应该有开始和关闭。
2. 缓冲区,也就是录制的声音放在哪里的问题。
二.DirectSound对录音的描述模型 (我装的是directx_dec2005_redist.exe)
1. DirectSound对录音的支持类
ØCapture,设备对象,可以看作是声卡的描述。
ØCaptureBuffer,缓冲区对象,存放录入的音频数据。
ØNotify,事件通知对象,由于录音是一个长时间的过程,因此使用一个缓冲队列(多个缓冲区)接收数据,每当一个缓冲区满的时候,系统使用这个对象通知应用程序取走这个缓冲区,并继续录音。
以上三个对象是进行录音操作的主要对象,由于在C++中对DirectSound的操作DirectX帮助文档中已经有很详细的说明,这里就不再赘述了。本文是针对Managed Code。除了以上三个主要的DirectSound类,还需要以下几个辅助类。
ØWaveFormat,描述了进行录制的声音波形的格式,例如采样率,单声道还是立体声,每个采样点的长度等等。
ØThread,线程类,由于录音的过程是需要不断处理缓冲区满的事件,因此新建一个线程对此进行单独处理。
ØAutoResetEvent,通知的事件,当缓冲区满的时候,使用该事件作为通知事件。
三.代码解析(SoundRecord类)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
5
using System.Windows.Forms;
6
using System.IO;
7
using System.Threading;
8
using Microsoft.DirectX;
9
using Microsoft.DirectX.DirectSound;
10![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
11![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
12
namespace DirectSoundTest
13![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
14
class SoundRecord
15![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
16
public const int cNotifyNum = 16; // 缓冲队列的数目
17
private int mNextCaptureOffset = 0; // 该次录音缓冲区的起始点
18
private int mSampleCount = 0; // 录制的样本数目
19
private int mNotifySize = 0; // 每次通知大小
20
private int mBufferSize = 0; // 缓冲队列大小
21
private string mFileName = string.Empty; // 文件名
22
private FileStream mWaveFile = null; // 文件流
23
private BinaryWriter mWriter = null; // 写文件
24
private Capture mCapDev = null; // 音频捕捉设备
25
private CaptureBuffer mRecBuffer = null; // 缓冲区对象
26
private Notify mNotify = null; // 消息通知对象
27
private WaveFormat mWavFormat; // 录音的格式
28
private Thread mNotifyThread = null; // 处理缓冲区消息的线程
29
private AutoResetEvent mNotificationEvent = null; // 通知事件
30![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
31![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
32![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
33![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
34
/// 构造函数,设定录音设备,设定录音格式.
35
/// </summary>
36
public SoundRecord()
37![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
38
// 初始化音频捕捉设备
39
InitCaptureDevice();
40
// 设定录音格式
41
mWavFormat = CreateWaveFormat();
42
}
43![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
44![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
45
/// 设定录音结束后保存的文件,包括路径
46
/// </summary>
47
/// <param name="filename">保存wav文件的路径名</param>
48
public void SetFileName(string filename)
49![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
50
mFileName = filename;
51
}
52![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
53![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
54
/// 开始录音
55
/// </summary>
56
public void RecStart()
57![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
58
// 创建录音文件
59
CreateSoundFile();
60![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
61
// 创建一个录音缓冲区,并开始录音
62
CreateCaptureBuffer();
63![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
64
// 建立通知消息,当缓冲区满的时候处理方法
65
InitNotifications();
66
mRecBuffer.Start(true);
67
}
68![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
69![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
70
/// 停止录音
71
/// </summary>
72
public void RecStop()
73![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
74
// 关闭通知消息
75
if (null != mNotificationEvent)
76
mNotificationEvent.Set();
77![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
78
// 停止录音
79
mRecBuffer.Stop();
80
// 写入缓冲区最后的数据
81
RecordCapturedData();
82![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
83
// 回写长度信息
84
mWriter.Seek(4, SeekOrigin.Begin);
85
mWriter.Write((int)(mSampleCount + 36)); // 写文件长度
86
mWriter.Seek(40, SeekOrigin.Begin);
87
mWriter.Write(mSampleCount); // 写数据长度
88
mWriter.Close();
89
mWaveFile.Close();
90
mWriter = null;
91
mWaveFile = null;
92
}
93![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
94
//4.内部调用函数
95![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
96![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
97
/// 初始化录音设备,此处使用主录音设备.
98
/// </summary>
99
/// <returns>调用成功返回true,否则返回false</returns>
100
private bool InitCaptureDevice()
101![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
102
// 获取默认音频捕捉设备
103
CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚举音频捕捉设备
104![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
105
Guid deviceGuid = Guid.Empty; // 音频捕捉设备的ID
106
if (devices.Count > 0)
107
deviceGuid = devices[0].DriverGuid;
108
else
109![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
110
MessageBox.Show("系统中没有音频捕捉设备");
111
return false;
112
}
113![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
114
// 用指定的捕捉设备创建Capture对象
115
try
116![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
117
mCapDev = new Capture(deviceGuid);
118
}
119
catch (DirectXException e)
120![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
121
MessageBox.Show(e.ToString());
122
return false;
123
}
124
return true;
125
}
126![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
127![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
128
/// 创建录音格式,此处使用16bit,16KHz,Mono的录音格式
129
/// </summary>
130
/// <returns>WaveFormat结构体</returns>
131
private WaveFormat CreateWaveFormat()
132![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
133
WaveFormat format = new WaveFormat();
134
format.FormatTag = WaveFormatTag.Pcm; // PCM
135
format.SamplesPerSecond = 16000; // 16KHz
136
format.BitsPerSample = 16; // 16Bit
137
format.Channels = 1; // Mono
138
format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));
139
format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;
140![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
141
return format;
142
}
143![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
144![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
145
/// 创建录音使用的缓冲区
146
/// </summary>
147
private void CreateCaptureBuffer()
148![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
149
// 缓冲区的描述对象
150
CaptureBufferDescription bufferdescription = new CaptureBufferDescription();
151![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
152
if (null != mNotify)
153![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
154
mNotify.Dispose();
155
mNotify = null;
156
}
157
if (null != mRecBuffer)
158![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
159
mRecBuffer.Dispose();
160
mRecBuffer = null;
161
}
162![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
163
// 设定通知的大小,默认为1s钟
164![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
165
mNotifySize = (1024 > mWavFormat.AverageBytesPerSecond / 8) ? 1024 : (mWavFormat.AverageBytesPerSecond / 8);
166
mNotifySize -= mNotifySize % mWavFormat.BlockAlign;
167![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
168![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
169
// 设定缓冲区大小
170
mBufferSize = mNotifySize * cNotifyNum;
171
// 创建缓冲区描述
172
bufferdescription.BufferBytes = mBufferSize;
173
bufferdescription.Format = mWavFormat; // 录音格式
174![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
175
// 创建缓冲区
176
mRecBuffer = new CaptureBuffer(bufferdescription, mCapDev);
177
mNextCaptureOffset = 0;
178
}
179![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
180![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
181
/// 初始化通知事件,将原缓冲区分成16个缓冲队列,在每个缓冲队列的结束点设定通知点.
182
/// </summary>
183
/// <returns>是否成功</returns>
184
private bool InitNotifications()
185![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
186
if (null == mRecBuffer)
187![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
188
MessageBox.Show("未创建录音缓冲区");
189
return false;
190![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
191
}
192
// 创建一个通知事件,当缓冲队列满了就激发该事件.
193
mNotificationEvent = new AutoResetEvent(false);
194
// 创建一个线程管理缓冲区事件
195
if (null == mNotifyThread)
196![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
197
mNotifyThread = new Thread(new ThreadStart(WaitThread));
198
mNotifyThread.Start();
199
}
200![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
201
// 设定通知的位置
202
BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1];
203
for (int i = 0; i < cNotifyNum; i++)
204![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
205
PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1;
206
PositionNotify[i].EventNotifyHandle = mNotificationEvent.Handle;
207
}
208![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
209
mNotify = new Notify(mRecBuffer);
210
mNotify.SetNotificationPositions(PositionNotify, cNotifyNum);
211
return true;
212
}
213![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
214![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
215
/// 将录制的数据写入wav文件
216
/// </summary>
217
private void RecordCapturedData()
218![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
219
byte[] CaptureData = null;
220
int ReadPos;
221
int CapturePos;
222
int LockSize;
223
mRecBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
224
LockSize = ReadPos - mNextCaptureOffset;
225
if (LockSize < 0)
226
LockSize += mBufferSize;
227![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
228
// 对齐缓冲区边界,实际上由于开始设定完整,这个操作是多余的.
229
LockSize -= (LockSize % mNotifySize);
230
if (0 == LockSize)
231
return;
232
// 读取缓冲区内的数据
233
CaptureData = (byte[])mRecBuffer.Read(mNextCaptureOffset, typeof(byte), LockFlag.None, LockSize);
234![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
235
// 写入Wav文件
236
mWriter.Write(CaptureData, 0, CaptureData.Length);
237![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
238
// 更新已经录制的数据长度.
239
mSampleCount += CaptureData.Length;
240
// 移动录制数据的起始点,通知消息只负责指示产生消息的位置,并不记录上次录制的位置
241
mNextCaptureOffset += CaptureData.Length;
242
mNextCaptureOffset %= mBufferSize; // Circular buffer
243
}
244![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
245![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
246![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
247
/// 接收缓冲区满消息的处理线程
248
/// </summary>
249
private void WaitThread()
250![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
251
while (true)
252![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
253
// 等待缓冲区的通知消息
254
mNotificationEvent.WaitOne(Timeout.Infinite, true);
255
// 录制数据
256
RecordCapturedData();
257
}
258
}
259![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
260![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
261
/// 创建保存的波形文件,并写入必要的文件头.
262
/// </summary>
263
private void CreateSoundFile()
264![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
265![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//**************************************************************************
266
Here is where the file will be created. A
267
wave file is a RIFF file, which has chunks
268
of data that describe what the file contains.
269
A wave RIFF file is put together like this:
270
The 12 byte RIFF chunk is constructed like this:
271
Bytes 0 - 3 : 'R' 'I' 'F' 'F'
272
Bytes 4 - 7 : Length of file, minus the first 8 bytes of the RIFF description.
273
(4 bytes for "WAVE" + 24 bytes for format chunk length +
274
8 bytes for data chunk description + actual sample data size.)
275
Bytes 8 - 11: 'W' 'A' 'V' 'E'
276
The 24 byte FORMAT chunk is constructed like this:
277
Bytes 0 - 3 : 'f' 'm' 't' ' '
278
Bytes 4 - 7 : The format chunk length. This is always 16.
279
Bytes 8 - 9 : File padding. Always 1.
280
Bytes 10- 11: Number of channels. Either 1 for mono, or 2 for stereo.
281
Bytes 12- 15: Sample rate.
282
Bytes 16- 19: Number of bytes per second.
283
Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or
284
16 bit mono, 4 for 16 bit stereo.
285
Bytes 22- 23: Number of bits per sample.
286
The DATA chunk is constructed like this:
287
Bytes 0 - 3 : 'd' 'a' 't' 'a'
288
Bytes 4 - 7 : Length of data, in bytes.
289
Bytes 8 -
: Actual sample data.
290
***************************************************************************/
291
// Open up the wave file for writing.
292
mWaveFile = new FileStream(mFileName, FileMode.Create);
293
mWriter = new BinaryWriter(mWaveFile);
294
// Set up file with RIFF chunk info.
295![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
char[] ChunkRiff =
{ 'R', 'I', 'F', 'F' };
296![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
char[] ChunkType =
{ 'W', 'A', 'V', 'E' };
297![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
char[] ChunkFmt =
{ 'f', 'm', 't', ' ' };
298![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
char[] ChunkData =
{ 'd', 'a', 't', 'a' };
299
short shPad = 1; // File padding
300
int nFormatChunkLength = 0x10; // Format chunk length.
301
int nLength = 0; // File length, minus first 8 bytes of RIFF description. This will be filled in later.
302
short shBytesPerSample = 0; // Bytes per sample.
303![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
304
// 一个样本点的字节数目
305
if (8 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels)
306
shBytesPerSample = 1;
307
else if ((8 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels) || (16 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels))
308
shBytesPerSample = 2;
309
else if (16 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels)
310
shBytesPerSample = 4;
311![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
312
// RIFF 块
313
mWriter.Write(ChunkRiff);
314
mWriter.Write(nLength);
315
mWriter.Write(ChunkType);
316
// WAVE块
317
mWriter.Write(ChunkFmt);
318
mWriter.Write(nFormatChunkLength);
319
mWriter.Write(shPad);
320
mWriter.Write(mWavFormat.Channels);
321
mWriter.Write(mWavFormat.SamplesPerSecond);
322
mWriter.Write(mWavFormat.AverageBytesPerSecond);
323
mWriter.Write(shBytesPerSample);
324
mWriter.Write(mWavFormat.BitsPerSample);
325![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
326
// 数据块
327
mWriter.Write(ChunkData);
328
mWriter.Write((int)0); // The sample length will be written in later.
329
}
330
}
331
}
5.外部窗体调用方式
声明部分:
private SoundRecord recorder = null; // 录音
窗体构造函数:
recorder = new SoundRecord();
启动录音按钮:
private void btnStart_Click(object sender, System.EventArgs e)
{
//
// 录音设置
//
string wavfile = null;
wavfile = “test.wav”;
recorder.SetFileName(wavfile);
recorder.RecStart();
}
中止录音按钮:
private void btnStop_Click(object sender, System.EventArgs e)
{
recorder.RecStop();
recorder = null;
}
6.需要添加的外部引用文件
在系统的System32目录下添加以下两个引用文件,如果没有,在DirectX的开发包内可以找到。
Microsoft.DirectX.dll
Microsoft.DirectX.DirectSound.dll