Windows WaveIn 錄音
- 設置採集音頻格式
- WAVEFORMATEX waveform;
- waveform.wFormatTag = WAVE_FORMAT_PCM;
- waveform.nSamplesPerSec = 8000;
- waveform.wBitsPerSample = 16;
- waveform.nChannels = 1;
- waveform.nAvgBytesPerSec = 16000;
- waveform.nBlockAlign = 2;
- waveform.cbSize = 0;
- 提早準備好的錄音數據緩存
- m_pRecoderBuf = new unsigned char[20 * 1024];
- m_recoderNum = 20;
- m_recoderBufLen = 20 * 1024;
- m_pWaveHdr = new WAVEHDR[20];
- memset(m_pRecoderBuf, 0, 20 * 1024);
- memset(m_pWaveHdr, 0, sizeof(WAVEHDR) * 20);
- 打開錄音設備
- MMRESULT mmres = waveInOpen(&m_hWaveIn, WAVE_MAPPER, &waveform, (DWORD_PTR)WaveInProc, (DWORD_PTR)this, CALLBACK_FUNCTION );
-
- if(mmres != MMSYSERR_NOERROR)
- {
-
- return;
- }
WAVE_MAPPER表示系統會本身尋找合適的錄音設備。
- 準備數據空間
- for (int i = 0; i < m_recoderNum; ++i)
- {
- m_pWaveHdr[i].lpData = (char*)m_pRecoderBuf + i * 1024;
- m_pWaveHdr[i].dwBufferLength = 1024;
- mmres = waveInPrepareHeader(m_hWaveIn, &m_pWaveHdr[i], sizeof(WAVEHDR));
- mmres = waveInAddBuffer(m_hWaveIn, &m_pWaveHdr[i], sizeof(WAVEHDR));
- }
- 開始錄音並打開寫文件
- mmres = waveInStart(m_hWaveIn);
-
- SYSTEMTIME systemtime;
- GetLocalTime(&systemtime);
- char filename[256];
- sprintf_s(filename, 256, "%d-%d-%d_%d_%d_%d.wav", systemtime.wYear, systemtime.wMonth, systemtime.wDay, systemtime.wHour, systemtime.wMinute, systemtime.wSecond);
- m_pWavFile = wav_write_open(filename, 8000, 16, 1);
- 要提早定義好數據接收回調函數,由於咱們用的是CALLBACK_FUNCTION
- static BOOL CALLBACK WaveInProc(HWAVEOUT hwo, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
- BOOL WaveInProcImpl(HWAVEOUT hwo, UINT uMsg, DWORD dwParam1, DWORD dwParam2);
函數裏的處理是:
- BOOL CAudioFileConvertDlg::WaveInProc(HWAVEOUT hwo, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
- {
- CAudioFileConvertDlg* pPlayer = (CAudioFileConvertDlg*)dwInstance;
-
- return pPlayer->WaveInProcImpl(hwo, uMsg, dwParam1, dwParam2);
- }
-
- BOOL CAudioFileConvertDlg::WaveInProcImpl(HWAVEOUT hwo, UINT uMsg, DWORD dwParam1, DWORD dwParam2)
- {
-
- if(uMsg == WIM_DATA)
- {
- LPWAVEHDR pHdr = (LPWAVEHDR) dwParam1;
-
- MMRESULT mmres = waveInUnprepareHeader (m_hWaveIn, pHdr, sizeof(WAVEHDR));
-
- if (NULL != m_pWavFile)
- {
- wav_write_data(m_pWavFile, (unsigned char *)(pHdr->lpData), pHdr->dwBytesRecorded);
- }
-
- mmres = waveInPrepareHeader(m_hWaveIn, pHdr, sizeof(WAVEHDR));
- mmres = waveInAddBuffer(m_hWaveIn, pHdr, sizeof(WAVEHDR));
- }
-
- return TRUE;
- }
- 關閉錄音並關閉wav寫文件
- MMRESULT mmres = waveInStop(m_hWaveIn);
- mmres = waveInClose(m_hWaveIn);
- wav_write_close(m_pWavFile);
- if (NULL != m_pRecoderBuf)
- {
- delete []m_pRecoderBuf;
- m_pRecoderBuf = NULL;
- }
-
- if (NULL != m_pWaveHdr)
- {
- delete []m_pWaveHdr;
- m_pWaveHdr = NULL;
- }
歡迎關注本站公眾號,獲取更多信息