参考文档:
1:github上的一个开源代码:点击打开链接,因为存储音频需要自己写文件头部,所以这里借鉴了它的文件存储功能。
2:一个很有用的帖子代码:点击打开链接,虽然有点小瑕疵,但是下面有解答。
3:一个说明类的博客:点击打开链接
这里加一些说明:windows下多线程尽量用_beginthreadex而不是CreateThread,网上原因说的很详细。其次,在关闭录音时,一定不要对waveIn设备进行缓冲区操作,要不然容易生成死锁。示例代码如下:
创建终止拷贝线程的代码:(上文博客里面提示,不能在录音的回调函数里将数据写到文件,因此需要创建线程,单独拷贝)
bool stopRecording(const char *fileName, int nameSize){ char *fileNameTrue = (char *)malloc(sizeof(char)* (nameSize+1)); strcpy_s(fileNameTrue,nameSize+1, fileName); //终止录音 unsigned threadID; hAudio_Detect_Thread = (HANDLE)_beginthreadex(NULL, 0, &Audio_Detect, fileNameTrue, 0, &threadID); WaitForSingleObject(hAudio_Detect_Thread, INFINITE); CloseHandle(hAudio_Detect_Thread); return true; }
void processSamples() { if(bRecordingStarted ){ waveInUnprepareHeader(hWaveIn, WaveHeaders[iBuffIdx], sizeof(WAVEHDR)); iBuffIdx ++; if (iBuffIdx == BUFFERCOUNT) { iBuffIdx = 0; } WaveHeaders[iBuffIdxT]->dwBufferLength = WaveBufSize; WaveHeaders[iBuffIdxT]->dwFlags = 0; WaveHeaders[iBuffIdxT]->dwLoops = 0; waveInPrepareHeader(hWaveIn, WaveHeaders[iBuffIdxT], sizeof(WAVEHDR)); waveInAddBuffer(hWaveIn, WaveHeaders[iBuffIdxT], sizeof(WAVEHDR)); if (iBuffIdxT == BUFFERCOUNT) { iBuffIdxT = 0; } } }
void writeData(char *name){ //停止录音 printf("进入写的函数里面了, the name is %s\n", name); bRecordingStarted = false; waveInReset(hWaveIn); int stopcode = waveInStop(hWaveIn); printf("the stopcode is %d\n", stopcode); COutputFile *file = NULL; file = new CWaveOutputFile; if (!file->Create(name, m_waveformin)) { printf("初始化就错误了\n"); } printf("正在写数据\n"); file->WriteData(m_AudioDataPool.lpdata, m_AudioDataPool.dwLength); printf("the length of m_AudioDataPool.length is %d", m_AudioDataPool.dwLength); file->Flush(); //释放资源 free(name); free(m_AudioDataPool.lpdata); m_AudioDataPool.lpdata = NULL; m_AudioDataPool.dwLength = 0; }
原文地址:http://blog.csdn.net/helius_sun/article/details/43611369