運用Microsoft.DirectX.DirectSound和Microsoft.DirectX實現簡單的錄音功能


1、首先要使用Microsoft.DirectX.DirectSound和Microsoft.DirectX這兩個dll進行錄音,需要先安裝microsoft directx 9.0cz這個組件,

百度雲盤下載地址:http://pan.baidu.com/s/1bpgbdP9,里面包含安裝程序和兩個dll

2、編寫錄音程序功能

1)編寫錄音支持的輔助類SoundRecord

源碼:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;

namespace SoundRecord
{
    public class SoundRecord
    {
        // 對DirectSound的支持
        int cNotifyNum = 16;       // 緩沖隊列的數目
        int mNextCaptureOffset = 0;      // 該次錄音緩沖區的起始點
        int mSampleCount = 0;            // 錄制的樣本數目
        int mNotifySize = 0;             // 每次通知大小
        int mBufferSize = 0;             // 緩沖隊列大小
        string mFileName = string.Empty;     // 文件名
        FileStream mWaveFile = null;         // 文件流
        BinaryWriter mWriter = null;         // 寫文件
        Capture mCapDev = null;              // 音頻捕捉設備
        CaptureBuffer mRecBuffer = null;     // 緩沖區對象
        Notify mNotify = null;               // 消息通知對象
        WaveFormat mWavFormat;                       // 錄音的格式
        Thread mNotifyThread = null;                 // 處理緩沖區消息的線程
        AutoResetEvent mNotificationEvent = null;    // 通知事件

        /// <summary>
        /// 構造函數,設定錄音設備,設定錄音格式.
        /// </summary>
        public SoundRecord()
        {
            // 初始化音頻捕捉設備
            InitCaptureDevice();
            // 設定錄音格式
            mWavFormat = CreateWaveFormat();
        }

        /// <summary>
        /// 設定錄音結束后保存的文件,包括路徑
        /// </summary>
        /// <param name="filename">保存wav文件的路徑名</param>
        public void SetFileName(string filename)
        {
            mFileName = filename;
        }

        /// <summary>
        /// 開始錄音
        /// </summary>
        public void RecStart()
        {
            // 創建錄音文件
            CreateSoundFile();
            // 創建一個錄音緩沖區,並開始錄音
            CreateCaptureBuffer();
            // 建立通知消息,當緩沖區滿的時候處理方法
            InitNotifications();
            mRecBuffer.Start(true);
        }

        /// <summary>
        /// 停止錄音
        /// </summary>
        public void RecStop()
        {
            // 關閉通知消息
            if (null != mNotificationEvent)
                mNotificationEvent.Set();
            // 停止錄音
            mRecBuffer.Stop();

            // 寫入緩沖區最后的數據
            RecordCapturedData();

            // 回寫長度信息
            mWriter.Seek(4, SeekOrigin.Begin);
            mWriter.Write((int)(mSampleCount + 36));   // 寫文件長度
            mWriter.Seek(40, SeekOrigin.Begin);
            mWriter.Write(mSampleCount);                // 寫數據長度
            mWriter.Close();
            mWaveFile.Close();
            mWriter = null;
            mWaveFile = null;
        }

        /// <summary>
        /// 初始化錄音設備,此處使用主錄音設備.
        /// </summary>
        /// <returns>調用成功返回true,否則返回false</returns>
        bool InitCaptureDevice()
        {
            // 獲取默認音頻捕捉設備
            CaptureDevicesCollection devices = new CaptureDevicesCollection(); // 枚舉音頻捕捉設備
            Guid deviceGuid = Guid.Empty;                                       // 音頻捕捉設備的ID
            if (devices.Count>0)
                deviceGuid = devices[0].DriverGuid;

            else
            {
                MessageBox.Show("系統中沒有音頻捕捉設備");
                return false;
            }

            // 用指定的捕捉設備創建Capture對象
            try
            {
                mCapDev = new Capture(deviceGuid);
            }
            catch(DirectXException e)
            {
                MessageBox.Show(e.ToString());
                return false;
            }
            return true;
        }

        /// <summary>
        /// 創建錄音格式,此處使用16bit,16KHz,Mono的錄音格式
        /// </summary>
        /// <returns>WaveFormat結構體</returns>
        private WaveFormat CreateWaveFormat()
        {
            WaveFormat format = new WaveFormat();
            format.FormatTag = WaveFormatTag.Pcm;   // PCM
            format.SamplesPerSecond = 16000;        // 16KHz
            format.BitsPerSample = 16;              // 16Bit
            format.Channels = 1;                    // Mono
            format.BlockAlign = (short)(format.Channels * (format.BitsPerSample / 8));
            format.AverageBytesPerSecond = format.BlockAlign * format.SamplesPerSecond;
            return format;
        }

        /// <summary>
        /// 創建錄音使用的緩沖區
        /// </summary>
        private void CreateCaptureBuffer()
        {
            // 緩沖區的描述對象
            CaptureBufferDescription bufferdescription = new CaptureBufferDescription();
            if (null != mNotify)
            {
                mNotify.Dispose();
                mNotify = null;
            }
            if (null != mRecBuffer)
            {
                mRecBuffer.Dispose();
                mRecBuffer = null;
            }
            // 設定通知的大小,默認為1s鍾
            mNotifySize = (1024 > mWavFormat.AverageBytesPerSecond / 8) ? 1024 : (mWavFormat.AverageBytesPerSecond / 8);
            mNotifySize -= mNotifySize % mWavFormat.BlockAlign;  

            // 設定緩沖區大小
            mBufferSize = mNotifySize * cNotifyNum;

            // 創建緩沖區描述           
            bufferdescription.BufferBytes = mBufferSize;
            bufferdescription.Format = mWavFormat;           // 錄音格式

            // 創建緩沖區
            mRecBuffer = new CaptureBuffer(bufferdescription, mCapDev);
            mNextCaptureOffset = 0;
        }

        /// <summary>
        /// 初始化通知事件,將原緩沖區分成16個緩沖隊列,在每個緩沖隊列的結束點設定通知點.
        /// </summary>
        /// <returns>是否成功</returns>
        private bool InitNotifications()
        {
            if (null == mRecBuffer)
            {
                MessageBox.Show("未創建錄音緩沖區");
                return false;
            }       

            // 創建一個通知事件,當緩沖隊列滿了就激發該事件.
            mNotificationEvent = new AutoResetEvent(false);
            // 創建一個線程管理緩沖區事件
            if (null == mNotifyThread)
            {
                mNotifyThread = new Thread(new ThreadStart(WaitThread));
                mNotifyThread.Start();
            }

            // 設定通知的位置
            BufferPositionNotify[] PositionNotify = new BufferPositionNotify[cNotifyNum + 1];
            for (int i = 0; i < cNotifyNum; i++)
            {
                PositionNotify[i].Offset = (mNotifySize * i) + mNotifySize - 1;
                PositionNotify[i].EventNotifyHandle = mNotificationEvent.Handle;               
            }

            mNotify = new Notify(mRecBuffer);
            mNotify.SetNotificationPositions(PositionNotify, cNotifyNum);
            return true;
        }

        /// <summary>
        /// 將錄制的數據寫入wav文件
        /// </summary>
        private void RecordCapturedData()
        {
            byte[] CaptureData = null;
            int ReadPos;
            int CapturePos;
            int LockSize;
            mRecBuffer.GetCurrentPosition(out CapturePos, out ReadPos);
            LockSize = ReadPos - mNextCaptureOffset;
            if (LockSize < 0)
                LockSize += mBufferSize;

            // 對齊緩沖區邊界,實際上由於開始設定完整,這個操作是多余的.
            LockSize -= (LockSize % mNotifySize);
            if (0 == LockSize)
                return;         

            // 讀取緩沖區內的數據
            CaptureData = (byte[])mRecBuffer.Read(mNextCaptureOffset, typeof(byte), LockFlag.None, LockSize);
            // 寫入Wav文件
            mWriter.Write(CaptureData, 0, CaptureData.Length);
            // 更新已經錄制的數據長度.
            mSampleCount += CaptureData.Length;
            // 移動錄制數據的起始點,通知消息只負責指示產生消息的位置,並不記錄上次錄制的位置
            mNextCaptureOffset += CaptureData.Length;
            mNextCaptureOffset %= mBufferSize; // Circular buffer
        }

        /// <summary>
        /// 接收緩沖區滿消息的處理線程
        /// </summary>
        private void WaitThread()
        {
            while(true)
            {
                // 等待緩沖區的通知消息
                mNotificationEvent.WaitOne(Timeout.Infinite, true);
                // 錄制數據
                RecordCapturedData();
           }
        }

        /// <summary>
        /// 創建保存的波形文件,並寫入必要的文件頭.
        /// </summary>
        private void CreateSoundFile()
        {
            // Open up the wave file for writing.
            mWaveFile = new FileStream(mFileName, FileMode.Create);
            mWriter = new BinaryWriter(mWaveFile);

            // Set up file with RIFF chunk info.
            char[] ChunkRiff = {'R','I','F','F'};
            char[] ChunkType = {'W','A','V','E'};
            char[] ChunkFmt = {'f','m','t',' '};
            char[] ChunkData = {'d','a','t','a'};
        
            short shPad = 1;                // File padding
            int nFormatChunkLength = 0x10; // Format chunk length.
            int nLength = 0;                // File length, minus first 8 bytes of RIFF description. This will be filled in later.
            short shBytesPerSample = 0;     // Bytes per sample.

            // 一個樣本點的字節數目
            if (8 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels)
                shBytesPerSample = 1;
            else if ((8 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels) || (16 == mWavFormat.BitsPerSample && 1 == mWavFormat.Channels))
                shBytesPerSample = 2;
            else if (16 == mWavFormat.BitsPerSample && 2 == mWavFormat.Channels)
                shBytesPerSample = 4;

            // RIFF 塊
            mWriter.Write(ChunkRiff);
            mWriter.Write(nLength);
            mWriter.Write(ChunkType);

            // WAVE塊
            mWriter.Write(ChunkFmt);
            mWriter.Write(nFormatChunkLength);
            mWriter.Write(shPad);
            mWriter.Write(mWavFormat.Channels);
            mWriter.Write(mWavFormat.SamplesPerSecond);
            mWriter.Write(mWavFormat.AverageBytesPerSecond);
            mWriter.Write(shBytesPerSample);
            mWriter.Write(mWavFormat.BitsPerSample);          

            // 數據塊
            mWriter.Write(ChunkData);
            mWriter.Write((int)0);   // The sample length will be written in later.
        }
    }
}

2)調用方法的winform界面源碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.IO;
using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;

namespace SoundRecord
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private SoundRecord recorder = new SoundRecord();

        private void btnStart_Click(object sender, EventArgs e)
        {
            string wavfile = null;
            wavfile = "test.wav";
            recorder.SetFileName(wavfile);
            recorder.RecStart();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            recorder.RecStop();
            recorder = null;
        }   
    }
}

3)winform界面圖

4)生成后的錄音文件,在項目bin目錄下

5)用播放器播放錄音文件

附錄:

錄音的demo源碼下載地址:http://pan.baidu.com/s/1hslW5Je


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM