C#中使用DirectSound录音

来源:互联网 发布:淘宝迟迟不发货骗局 编辑:程序博客网 时间:2024/06/04 17:50

原文地址:http://blog.donews.com/uplook/archive/2005/12/14/657145.aspx

注:1.原文有程序终止后仍有线程在运行的情况,这里修正了下;

        2.DirectSound录音详细介绍:http://blog.csdn.net/woaixiaozhe/article/details/7863007

        3."Mixed mode assembly is built against version 'v1.1.4322' of the runtime and......"问题解决方案见:http://blog.csdn.net/woaixiaozhe/article/details/7864391

 

一.声卡录音的基本原理

为了实现一个录音的基本过程,至少需要以下对象的支持:

1.   录音设备,对我们的PC设备就是声卡。这个录音设备可以进行的操作应该有开始和关闭。

2.   缓冲区,也就是录制的声音放在哪里的问题。

 

二.DirectSound对录音的描述模型

1.   DirectSound对录音的支持类

Ø         Capture,设备对象,可以看作是声卡的描述。

Ø         CaptureBuffer,缓冲区对象,存放录入的音频数据。

Ø         Notify,事件通知对象,由于录音是一个长时间的过程,因此使用一个缓冲队列(多个缓冲区)接收数据,每当一个缓冲区满的时候,系统使用这个对象通知应用程序取走这个缓冲区,并继续录音。

以上三个对象是进行录音操作的主要对象,由于在C++中对DirectSound的操作DirectX帮助文档中已经有很详细的说明,这里就不再赘述了。本文是针对Managed Code。除了以上三个主要的DirectSound类,还需要以下几个辅助类。

Ø         WaveFormat,描述了进行录制的声音波形的格式,例如采样率,单声道还是立体声,每个采样点的长度等等。

Ø         Thread,线程类,由于录音的过程是需要不断处理缓冲区满的事件,因此新建一个线程对此进行单独处理。

Ø         AutoResetEvent,通知的事件,当缓冲区满的时候,使用该事件作为通知事件。

 

三.代码解析(SoundRecord类)

1.需要引用的程序集

[csharp] view plain copy
  1. #region 成员数据  
  2.     private Capture mCapDev = null;              // 音频捕捉设备  
  3.     private CaptureBuffer mRecBuffer = null;     // 缓冲区对象  
  4.     private WaveFormat mWavFormat;               // 录音的格式  
  5.   
  6.     private int mNextCaptureOffset = 0;         // 该次录音缓冲区的起始点  
  7.     private int mSampleCount = 0;               // 录制的样本数目  
  8.   
  9.     private Notify mNotify = null;               // 消息通知对象  
  10.     public const int cNotifyNum = 16;           // 通知的个数  
  11.     private int mNotifySize = 0;                // 每次通知大小  
  12.     private int mBufferSize = 0;                // 缓冲队列大小  
  13.     private Thread mNotifyThread = null;                 // 处理缓冲区消息的线程  
  14.     private AutoResetEvent mNotificationEvent = null;    // 通知事件  
  15.   
  16.     private string mFileName = string.Empty;     // 文件保存路径  
  17.     private FileStream mWaveFile = null;         // 文件流  
  18.     private BinaryWriter mWriter = null;         // 写文件  
  19. #endregion  


3.   对外操作的函数

[csharp] view plain copy
  1. #region 对外操作函数  
  2.     /// <summary>  
  3.     /// 构造函数,设定录音设备,设定录音格式.  
  4.     /// <summary>  
  5.     public SoundRecorder()  
  6.     {  
  7.         // 初始化音频捕捉设备  
  8.         InitCaptureDevice();  
  9.         // 设定录音格式  
  10.         mWavFormat = CreateWaveFormat();  
  11.     }  
  12.   
  13.     /// <summary>  
  14.     /// 创建录音格式,此处使用16bit,16KHz,Mono的录音格式  
  15.     /// <summary>  
  16.     private WaveFormat CreateWaveFormat()  
  17.     {  
  18.         WaveFormat format = new WaveFormat();  
  19.         format.FormatTag = WaveFormatTag.Pcm;   // PCM  
  20.         format.SamplesPerSecond = 16000;        // 采样率:16KHz  
  21.         format.BitsPerSample = 16;              // 采样位数:16Bit  
  22.         format.Channels = 1;                    // 声道:Mono  
  23.         format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));  // 单位采样点的字节数   
  24.         format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;  
  25.         return format;  
  26.         // 按照以上采样规格,可知采样1秒钟的字节数为 16000*2=32000B 约为31K  
  27.     }  
  28.   
  29.     /// <summary>  
  30.     /// 设定录音结束后保存的文件,包括路径  
  31.     /// </summary>  
  32.     /// <param name="filename">保存wav文件的路径名</param>  
  33.     public void SetFileName(string filename)  
  34.     {  
  35.         mFileName = filename;  
  36.     }  
  37.   
  38.     /// <summary>  
  39.     /// 开始录音  
  40.     /// </summary>  
  41.     public void RecStart()  
  42.     {  
  43.         // 创建录音文件  
  44.         CreateSoundFile();  
  45.         // 创建一个录音缓冲区,并开始录音  
  46.         CreateCaptureBuffer();  
  47.         // 建立通知消息,当缓冲区满的时候处理方法  
  48.         InitNotifications();  
  49.         mRecBuffer.Start(true);  
  50.     }  
  51.   
  52.   
  53.     /// <summary>  
  54.     /// 停止录音  
  55.     /// </summary>  
  56.     public void RecStop()  
  57.     {  
  58.         mRecBuffer.Stop();      // 调用缓冲区的停止方法,停止采集声音  
  59.         if (null != mNotificationEvent)  
  60.             mNotificationEvent.Set();       //关闭通知  
  61.         mNotifyThread.Abort();  //结束线程  
  62.         RecordCapturedData();   // 将缓冲区最后一部分数据写入到文件中  
  63.   
  64.         // 写WAV文件尾  
  65.         mWriter.Seek(4, SeekOrigin.Begin);  
  66.         mWriter.Write((int)(mSampleCount + 36));   // 写文件长度  
  67.         mWriter.Seek(40, SeekOrigin.Begin);  
  68.         mWriter.Write(mSampleCount);                // 写数据长度  
  69.   
  70.         mWriter.Close();  
  71.         mWaveFile.Close();  
  72.         mWriter = null;  
  73.         mWaveFile = null;  
  74.     }  
  75. dregion  



4.内部调用函数

[csharp] view plain copy
  1.    #region 对内操作函数  
  2.        /// <summary>  
  3.        /// 初始化录音设备,此处使用主录音设备.  
  4.        /// </summary>  
  5.        /// <returns>调用成功返回true,否则返回false</returns>  
  6.        private bool InitCaptureDevice()  
  7.        {  
  8.            // 获取默认音频捕捉设备  
  9.            CaptureDevicesCollection devices = new CaptureDevicesCollection();  // 枚举音频捕捉设备  
  10.            Guid deviceGuid = Guid.Empty;    
  11.   
  12.            if (devices.Count>0)  
  13.                deviceGuid = devices[0].DriverGuid;  
  14.            else  
  15.            {  
  16.                MessageBox.Show("系统中没有音频捕捉设备");  
  17.                return false;  
  18.            }  
  19.   
  20.            // 用指定的捕捉设备创建Capture对象  
  21.            try  
  22.            {  
  23.                mCapDev = new Capture(deviceGuid);  
  24.            }  
  25.            catch (DirectXException e)  
  26.            {  
  27.                MessageBox.Show(e.ToString());  
  28.                return false;  
  29.            }  
  30.            return true;  
  31.        }  
  32.   
  33.        /// <summary>  
  34.        /// 创建录音使用的缓冲区  
  35.        /// </summary>  
  36.        private void CreateCaptureBuffer()  
  37.        {  
  38.            // 缓冲区的描述对象  
  39.            CaptureBufferDescription bufferdescription = new CaptureBufferDescription();  
  40.            if (null != mNotify)  
  41.            {  
  42.                mNotify.Dispose();  
  43.                mNotify = null;  
  44.            }  
  45.            if (null != mRecBuffer)  
  46.            {  
  47.                mRecBuffer.Dispose();  
  48.                mRecBuffer = null;  
  49.            }  
  50.            // 设定通知的大小,默认为1s钟  
  51.            mNotifySize = (1024 > mWavFormat.AverageBytesPerSecond/8) ? 1024 : (mWavFormat.AverageBytesPerSecond / 8);  
  52.            mNotifySize -= mNotifySize % mWavFormat.BlockAlign;    
  53.            // 设定缓冲区大小  
  54.            mBufferSize = mNotifySize * cNotifyNum;  
  55.            // 创建缓冲区描述  
  56.            bufferdescription.BufferBytes = mBufferSize;  
  57.            bufferdescription.Format = mWavFormat;           // 录音格式  
  58.            // 创建缓冲区  
  59.            mRecBuffer = new CaptureBuffer(bufferdescription, mCapDev);  
  60.            mNextCaptureOffset = 0;  
  61.        }  
  62.   
  63.        /// <summary>  
  64.        /// 初始化通知事件,将原缓冲区分成16个缓冲队列,在每个缓冲队列的结束点设定通知点.  
  65.        /// </summary>  
  66.        /// <returns>是否成功</returns>  
  67.        private bool InitNotifications()  
  68.        {  
  69.            if (null == mRecBuffer)  
  70.            {  
  71.                MessageBox.Show("未创建录音缓冲区");  
  72.                return false;  
  73.            }  
  74.            // 创建一个通知事件,当缓冲队列满了就激发该事件.  
  75.            mNotificationEvent = new AutoResetEvent(false);  
  76.            // 创建一个线程管理缓冲区事件  
  77.            if (null == mNotifyThread)  
  78.            {  
  79.                mNotifyThread = new Thread(new ThreadStart(WaitThread));  
  80.                mNotifyThread.Start();  
  81.            }  
  82.            // 设定通知的位置  
  83.            BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1];  
  84.            for (int i = 0; i < cNotifyNum; i++)  
  85.            {  
  86.                PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1;  
  87.                PositionNotify[i].EventNotifyHandle = mNotificationEvent.SafeWaitHandle.DangerousGetHandle();              
  88.            }  
  89.            mNotify = new Notify(mRecBuffer);  
  90.            mNotify.SetNotificationPositions(PositionNotify, cNotifyNum);  
  91.            return true;  
  92.        }  
  93.   
  94.        /// <summary>  
  95.        /// 接收缓冲区满消息的处理线程  
  96.        /// </summary>  
  97.        private void WaitThread()  
  98.        {  
  99.            while (true)  
  100.            {  
  101.                // 等待缓冲区的通知消息  
  102.                mNotificationEvent.WaitOne(Timeout.Infinite, true);  
  103.                // 录制数据  
  104.                RecordCapturedData();  
  105.            }  
  106.        }  
  107.   
  108.        /// <summary>  
  109.        /// 将录制的数据写入wav文件  
  110.        /// </summary>  
  111.        private void RecordCapturedData()  
  112.        {  
  113.            byte[] CaptureData = null;  
  114.            int ReadPos=0, CapturePos=0, LockSize=0;  
  115.            mRecBuffer.GetCurrentPosition(out CapturePos, out ReadPos);  
  116.            LockSize = ReadPos - mNextCaptureOffset;  
  117.            if (LockSize < 0)       // 因为是循环的使用缓冲区,所以有一种情况下为负:当文以载读指针回到第一个通知点,而Ibuffeoffset还在最后一个通知处  
  118.                LockSize += mBufferSize;  
  119.            LockSize -= (LockSize % mNotifySize);   // 对齐缓冲区边界,实际上由于开始设定完整,这个操作是多余的.  
  120.            if (0 == LockSize)  
  121.                return;  
  122.     
  123.            // 读取缓冲区内的数据  
  124.            CaptureData = (byte[])mRecBuffer.Read(mNextCaptureOffset, typeof(byte), LockFlag.None, LockSize);  
  125.            // 写入Wav文件  
  126.            mWriter.Write(CaptureData, 0, CaptureData.Length);  
  127.            // 更新已经录制的数据长度.  
  128.            mSampleCount += CaptureData.Length;  
  129.            // 移动录制数据的起始点,通知消息只负责指示产生消息的位置,并不记录上次录制的位置  
  130.            mNextCaptureOffset += CaptureData.Length;  
  131.            mNextCaptureOffset %= mBufferSize; // Circular buffer  
  132.        }  
  133.   
  134.        /// <summary>  
  135.        /// 创建保存的波形文件,并写入必要的文件头.  
  136.        /// </summary>  
  137.        private void CreateSoundFile()  
  138.        {  
  139.            // Open up the wave file for writing.  
  140.            mWaveFile = new FileStream(mFileName, FileMode.Create);  
  141.            mWriter = new BinaryWriter(mWaveFile);  
  142.            /**************************************************************************  
  143.               Here is where the file will be created. A  
  144.               wave file is a RIFF file, which has chunks  
  145.               of data that describe what the file contains.  
  146.               A wave RIFF file is put together like this:  
  147.               The 12 byte RIFF chunk is constructed like this:  
  148.               Bytes 0 - 3 :  'R' 'I' 'F' 'F'  
  149.               Bytes 4 - 7 :  Length of file, minus the first 8 bytes of the RIFF description.  
  150.                                 (4 bytes for "WAVE" + 24 bytes for format chunk length +  
  151.                                 8 bytes for data chunk description + actual sample data size.)  
  152.                Bytes 8 - 11: 'W' 'A' 'V' 'E'  
  153.                The 24 byte FORMAT chunk is constructed like this:  
  154.                Bytes 0 - 3 : 'f' 'm' 't' ' '  
  155.                Bytes 4 - 7 : The format chunk length. This is always 16.  
  156.                Bytes 8 - 9 : File padding. Always 1.  
  157.                Bytes 10- 11: Number of channels. Either 1 for mono,  or 2 for stereo.  
  158.                Bytes 12- 15: Sample rate.  
  159.                Bytes 16- 19: Number of bytes per second.  
  160.                Bytes 20- 21: Bytes per sample. 1 for 8 bit mono, 2 for 8 bit stereo or  
  161.                                16 bit mono, 4 for 16 bit stereo.  
  162.                Bytes 22- 23: Number of bits per sample.  
  163.                The DATA chunk is constructed like this:  
  164.                Bytes 0 - 3 : 'd' 'a' 't' 'a'  
  165.                Bytes 4 - 7 : Length of data, in bytes.  
  166.                Bytes 8 -: Actual sample data.  
  167.              ***************************************************************************/    
  168.             // Set up file with RIFF chunk info.  
  169.            char[] ChunkRiff = {'R''I','F','F'};  
  170.            char[] ChunkType = {'W','A','V','E'};  
  171.            char[] ChunkFmt  = {'f','m','t',' '};  
  172.            char[] ChunkData = {'d','a','t','a'};  
  173.     
  174.            short shPad = 1;                // File padding  
  175.            int nFormatChunkLength = 0x10;  // Format chunk length.  
  176.            int nLength = 0;                // File length, minus first 8 bytes of RIFF description. This will be filled in later.  
  177.            short shBytesPerSample = 0;     // Bytes per sample.  
  178.   
  179.            // 一个样本点的字节数目  
  180.            if (8 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels)  
  181.                shBytesPerSample = 1;  
  182.            else if ((8 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels) || (16 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels))  
  183.                shBytesPerSample = 2;  
  184.            else if (16 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels)  
  185.                shBytesPerSample = 4;  
  186.   
  187.            // RIFF 块  
  188.            mWriter.Write(ChunkRiff);  
  189.            mWriter.Write(nLength);  
  190.            mWriter.Write(ChunkType);  
  191.   
  192.            // WAVE块  
  193.            mWriter.Write(ChunkFmt);  
  194.            mWriter.Write(nFormatChunkLength);  
  195.            mWriter.Write(shPad);  
  196.            mWriter.Write(mWavFormat.Channels);  
  197.            mWriter.Write(mWavFormat.SamplesPerSecond);  
  198.            mWriter.Write(mWavFormat.AverageBytesPerSecond);  
  199.            mWriter.Write(shBytesPerSample);  
  200.            mWriter.Write(mWavFormat.BitsPerSample);  
  201.     
  202.            // 数据块  
  203.            mWriter.Write(ChunkData);  
  204.            mWriter.Write((int)0);   // The sample length will be written in later.  
  205.        }  
  206. #endregion  


5.外部窗体调用方式

    声明部分:

[csharp] view plain copy
  1. private SoundRecord recorder = null;    // 录音  

    窗体构造函数:

[csharp] view plain copy
  1. recorder = new SoundRecord();  

    启动录音按钮:

[csharp] view plain copy
  1. private void btnStart_Click(object sender, System.EventArgs e)  
  2. {  
  3.     //  
  4.     // 录音设置  
  5.     //  
  6.     string wavfile = null;  
  7.     wavfile = “test.wav”;  
  8.     recorder.SetFileName(wavfile);  
  9.     recorder.RecStart();  
  10. }  

    中止录音按钮:

[csharp] view plain copy
  1. private void btnStop_Click(object sender, System.EventArgs e)  
  2. {  
  3.     recorder.RecStop();  
  4.     recorder = null;  
  5. }  
 

6.需要添加的外部引用文件

在系统的System32目录下添加以下两个引用文件,如果没有,在DirectX的开发包内可以找到。

Microsoft.DirectX.dll

Microsoft.DirectX.DirectSound.dll


评论也贴过来吧:

6条评论

  1. 请问一下 有没有方法判断音量大小? 我想做一个,判断音量大小的来录音,避免无声音录制

  2. 你好,看了你的哪个DX录音,然后自己动手试验了一下,程序运行不起来,有错误,不知道怎么改!

  3. 运行没问题,只不过btnStop_Click后有线程没有结束,还没仔细看,不过还是来谢谢下。

  4. private void WaitThread()

    中while里写了ture,使这个循环一直出不来,mNotifyThread这个线程无法结束

  5. 博主,我使用你那个类,做了个应用程序,可以正常录音;

    可我把MessageBox.Show换成throw new Exception后,然后改成window服务,可以录音,但没一点声音,咋回事呀??? (我是一个简单的window服务,服务是完全正常无错的)

  6. 这样做能实现B/S网页录音吗?

 

 转自:http://blog.csdn.net/woaixiaozhe/article/details/7852824/

0 0