Recording audio in windows and recording audio in windows
Reference:
1: Open Source Code on github: Click to open the link. Because you need to write your own file header to store audio, the file storage function is used for reference here.
2: A very useful post code: Click to open the link, although a little flaw, but there are answers below.
3: A descriptive blog: Click to open the link
Here are some instructions: Use _ beginthreadex instead of CreateThread as much as possible for multithreading in windows. The online reasons are very detailed. Second, when you disable the recording, do not perform buffer operations on the waveIn device, or else it is easy to generate a deadlock. The sample code is as follows:
Code for creating and terminating the copy thread: (The above blog prompts that data cannot be written to a file in the recording callback function. Therefore, you need to create a thread and copy it separately)
Bool stopRecording (const char * fileName, int nameSize) {char * fileNameTrue = (char *) malloc (sizeof (char) * (nameSize + 1); strcpy_s (fileNameTrue, nameSize + 1, fileName); // terminate the recording 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 ;}
The code for changing the buffer module for the waveIn device. Note that the minimum number of buffer modules is four. Too few buffer modules may cause problems such as noises.
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;}}}
The data writing function mainly calls the code on github.
Void writeData (char * name) {// stop the recording printf ("Enter the writing function, 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 ("initialization error \ n");} printf ("writing data \ n "); file-> WriteData (m_AudioDataPool.lpdata, m_AudioDataPool.dwLength); printf ("the length of m_AudioDataPool.length is % d", m_AudioDataPool.dwLength); file-> Flush (); // release the resource free (name); free (m_AudioDataPool.lpdata); m_AudioDataPool.lpdata = NULL; m_AudioDataPool.dwLength = 0 ;}