您的位置:首页 > 其它

DirectSound的例子程序CaptureSound(.NET version)的一个Bug

2007-09-13 18:23 411 查看
最近笔者在.NET平台上学着使用DirectSound来做一个简单的录音和WAV文件合并的功能, 当然DirectX自带的CaptureSound例子提供了一切录音的源代码,不过我发现其中有个Bug,导致Release版本的程序无辜退出。

DirectX SDK的版本: August 2007.

代码(位于文件MainForm.cs):
void InitNotifications()
{
//-----------------------------------------------------------------------------
// Name: InitNotifications()
// Desc: Inits the notifications on the capture buffer which are handled
// in the notify thread.
//-----------------------------------------------------------------------------
if (null == applicationBuffer)
throw new NullReferenceException();
// Create a thread to monitor the notify events
if (null == NotifyThread)
{
NotifyThread = new Thread(new ThreadStart(WaitThread));
Capturing = true;
NotifyThread.Start();

// Create a notification event, for when the sound stops playing
NotificationEvent = new AutoResetEvent(false);

}
// Setup the notification positions
for (int i = 0; i < NumberRecordNotifications; i++)
{
PositionNotify[i].Offset = (NotifySize * i) + NotifySize - 1;
PositionNotify[i].EventNotifyHandle = NotificationEvent.Handle;
}

applicationNotify = new Notify(applicationBuffer);
// Tell DirectSound when to notify the app. The notification will come in the from
// of signaled events that are handled in the notify thread.
applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);
}

private void WaitThread()
{
while(Capturing)
{
//Sit here and wait for a message to arrive
NotificationEvent.WaitOne(Timeout.Infinite, true);
RecordCapturedData();
}
}
注意,在WaitThread被第一次调用的时,也就是代码 NotifyThread.Start(),这个时刻NotificationEvent还没有被初始化,而在WaitThread中就直接调用了这个变量!而Visual Studio的强大之处在于,在Debug模式下,CLR可能优先执行了主线程,也就是这个变量随即被初始化了,导致这个问题无法被发觉。而在Release模式下,无论怎么写Catch,这个异常都会直接终止程序。

修正这个Bug非常简单:
// Create a notification event, for when the sound stops playing
NotificationEvent = new AutoResetEvent(false);

NotifyThread.Start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐