一.声卡录音的基本原理
为了实现一个录音的基本过程,至少需要以下对象的支持:
1. 录音设备,对我们的PC设备就是声卡。这个录音设备可以进行的操作应该有开始和关闭。
2. 缓冲区,也就是录制的声音放在哪里的问题。
二.DirectSound对录音的描述模型 (我装的是directx_dec2005_redist.exe)
1. DirectSound对录音的支持类
ØCapture,设备对象,可以看作是声卡的描述。
ØCaptureBuffer,缓冲区对象,存放录入的音频数据。
ØNotify,事件通知对象,由于录音是一个长时间的过程,因此使用一个缓冲队列(多个缓冲区)接收数据,每当一个缓冲区满的时候,系统使用这个对象通知应用程序取走这个缓冲区,并继续录音。
以上三个对象是进行录音操作的主要对象,由于在C++中对DirectSound的操作DirectX帮助文档中已经有很详细的说明,这里就不再赘述了。本文是针对Managed Code。除了以上三个主要的DirectSound类,还需要以下几个辅助类。
ØWaveFormat,描述了进行录制的声音波形的格式,例如采样率,单声道还是立体声,每个采样点的长度等等。
ØThread,线程类,由于录音的过程是需要不断处理缓冲区满的事件,因此新建一个线程对此进行单独处理。
ØAutoResetEvent,通知的事件,当缓冲区满的时候,使用该事件作为通知事件。
三.代码解析(SoundRecord类)
1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
using System.Windows.Forms;6
using System.IO;7
using System.Threading;8
using Microsoft.DirectX;9
using Microsoft.DirectX.DirectSound;10

11

12
namespace DirectSoundTest13


{14
class SoundRecord15

{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

31

32

33

/**//// <summary>34
/// 构造函数,设定录音设备,设定录音格式.35
/// </summary>36
public SoundRecord()37

{38
// 初始化音频捕捉设备39
InitCaptureDevice();40
// 设定录音格式41
mWavFormat = CreateWaveFormat();42
}43

44

/**//// <summary>45
/// 设定录音结束后保存的文件,包括路径46
/// </summary>47
/// <param name="filename">保存wav文件的路径名</param>48
public void SetFileName(string filename)49

{50
mFileName = filename;51
}52

53

/**//// <summary>54
/// 开始录音55
/// </summary>56
public void RecStart()57

{58
// 创建录音文件59
CreateSoundFile();60

61
// 创建一个录音缓冲区,并开始录音62
CreateCaptureBuffer();63

64
// 建立通知消息,当缓冲区满的时候处理方法65
InitNotifications();66
mRecBuffer.Start(true);67
}68

69

/**//// <summary>70
/// 停止录音71
/// </summary>72
public void RecStop()73

{74
// 关闭通知消息75
if (null != mNotificationEvent)76
mNotificationEvent.Set();77

78
// 停止录音79
mRecBuffer.Stop();80
// 写入缓冲区最后的数据81
RecordCapturedData();82

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

94
//4.内部调用函数95

96

/**//// <summary>97
/// 初始化录音设备,此处使用主录音设备.98
/// </summary>99
/// <returns>调用成功返回true,否则返回false</returns>100
private bool InitCaptureDevice()101

{102
// 获取默认音频捕捉设备103
CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚举音频捕捉设备104

105
Guid deviceGuid = Guid.Empty; // 音频捕捉设备的ID106
if (devices.Count > 0)107
deviceGuid = devices[0].DriverGuid;108
else109

{110
MessageBox.Show("系统中没有音频捕捉设备");111
return false;112
}113

114
// 用指定的捕捉设备创建Capture对象115
try116

{117
mCapDev = new Capture(deviceGuid);118
}119
catch (DirectXException e)120

{121
MessageBox.Show(e.ToString());122
return false;123
}124
return true;125
}126

127

/**//// <summary>128
/// 创建录音格式,此处使用16bit,16KHz,Mono的录音格式129
/// </summary>130
/// <returns>WaveFormat结构体</returns>131
private WaveFormat CreateWaveFormat()132

{133
WaveFormat format = new WaveFormat();134
format.FormatTag = WaveFormatTag.Pcm; // PCM135
format.SamplesPerSecond = 16000; // 16KHz136
format.BitsPerSample = 16; // 16Bit137
format.Channels = 1; // Mono138
format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));139
format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;140

141
return format;142
}143

144

/**//// <summary>145
/// 创建录音使用的缓冲区146
/// </summary>147
private void CreateCaptureBuffer()148

{149
// 缓冲区的描述对象150
CaptureBufferDescription bufferdescription = new CaptureBufferDescription();151

152
if (null != mNotify)153

{154
mNotify.Dispose();155
mNotify = null;156
}157
if (null != mRecBuffer)158

{159
mRecBuffer.Dispose();160
mRecBuffer = null;161
}162

163
// 设定通知的大小,默认为1s钟164

165
mNotifySize = (1024 > mWavFormat.AverageBytesPerSecond / 8) ? 1024 : (mWavFormat.AverageBytesPerSecond / 8);166
mNotifySize -= mNotifySize % mWavFormat.BlockAlign;167

168

169
// 设定缓冲区大小170
mBufferSize = mNotifySize * cNotifyNum;171
// 创建缓冲区描述 172
bufferdescription.BufferBytes = mBufferSize;173
bufferdescription.Format = mWavFormat; // 录音格式174

175
// 创建缓冲区 176
mRecBuffer = new CaptureBuffer(bufferdescription, mCapDev);177
mNextCaptureOffset = 0;178
}179

180

/**//// <summary>181
/// 初始化通知事件,将原缓冲区分成16个缓冲队列,在每个缓冲队列的结束点设定通知点.182
/// </summary>183
/// <returns>是否成功</returns>184
private bool InitNotifications()185

{186
if (null == mRecBuffer)187

{188
MessageBox.Show("未创建录音缓冲区");189
return false;190

191
}192
// 创建一个通知事件,当缓冲队列满了就激发该事件.193
mNotificationEvent = new AutoResetEvent(false);194
// 创建一个线程管理缓冲区事件195
if (null == mNotifyThread)196

{197
mNotifyThread = new Thread(new ThreadStart(WaitThread));198
mNotifyThread.Start();199
}200

201
// 设定通知的位置202
BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1];203
for (int i = 0; i < cNotifyNum; i++)204

{205
PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1;206
PositionNotify[i].EventNotifyHandle = mNotificationEvent.Handle;207
}208

209
mNotify = new Notify(mRecBuffer);210
mNotify.SetNotificationPositions(PositionNotify, cNotifyNum);211
return true;212
}213

214

/**//// <summary>215
/// 将录制的数据写入wav文件216
/// </summary>217
private void RecordCapturedData()218

{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

228
// 对齐缓冲区边界,实际上由于开始设定完整,这个操作是多余的.229
LockSize -= (LockSize % mNotifySize);230
if (0 == LockSize)231
return;232
// 读取缓冲区内的数据233
CaptureData = (byte[])mRecBuffer.Read(mNextCaptureOffset, typeof(byte), LockFlag.None, LockSize);234

235
// 写入Wav文件236
mWriter.Write(CaptureData, 0, CaptureData.Length);237

238
// 更新已经录制的数据长度.239
mSampleCount += CaptureData.Length;240
// 移动录制数据的起始点,通知消息只负责指示产生消息的位置,并不记录上次录制的位置241
mNextCaptureOffset += CaptureData.Length;242
mNextCaptureOffset %= mBufferSize; // Circular buffer243
}244

245

246

/**//// <summary>247
/// 接收缓冲区满消息的处理线程248
/// </summary>249
private void WaitThread()250

{251
while (true)252

{253
// 等待缓冲区的通知消息254
mNotificationEvent.WaitOne(Timeout.Infinite, true);255
// 录制数据256
RecordCapturedData();257
}258
}259

260

/**//// <summary>261
/// 创建保存的波形文件,并写入必要的文件头.262
/// </summary>263
private void CreateSoundFile()264

{265

/**//**************************************************************************266
Here is where the file will be created. A267
wave file is a RIFF file, which has chunks268
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 or284
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

char[] ChunkRiff =
{ 'R', 'I', 'F', 'F' };296

char[] ChunkType =
{ 'W', 'A', 'V', 'E' };297

char[] ChunkFmt =
{ 'f', 'm', 't', ' ' };298

char[] ChunkData =
{ 'd', 'a', 't', 'a' };299
short shPad = 1; // File padding300
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

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

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

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