基本步骤及思想:设定音频采集参数(采样率、声道等),打开音频设备和开辟缓存,操作采集的数据。
1. 定义音频采集参数
WAVEFORMATEX waveform;//WAVE波形的采集参数
typedef struct {
WORD wFormatTag;
WORD nChannels;
DWORD nSamplesPerSec;
DWORD nAvgBytesPerSec;
WORD nBlockAlign;
WORD wBitsPerSample;
WORD cbSize;
} WAVEFORMATEX;
waveform.wFormatTag=WAVE_FORMAT_PCM;
waveform.nChannels=1; //声道设为1
waveform.nSamplesPerSec=11025; //采样率11025
waveform.nAvgBytesPerSec=11025;
waveform.nBlockAlign=1;
waveform.wBitsPerSample=8; //数据位设为8位
waveform.cbSize=0;
PWAVEHDR pWaveHdr1,pWaveHdr2; //WAVE波形的头信息
2. 打开音频采集设备并开辟缓存
if (waveInOpen(&hWaveIn,WAVE_MAPPER,&waveform,(DWORD)this->m_hWnd,NULL,CALLBACK_WINDOW)) { //打开设备
free(pBuffer1);
free(pBuffer2);
MessageBeep(MB_ICONEXCLAMATION);
AfxMessageBox("Audio can not be open!");
}
pWaveHdr1->lpData=(LPTSTR)pBuffer1;
pWaveHdr1->dwBufferLength=INP_BUFFER_SIZE;
pWaveHdr1->dwBytesRecorded=0;
pWaveHdr1->dwUser=0;
pWaveHdr1->dwFlags=0;
pWaveHdr1->dwLoops=1;
pWaveHdr1->lpNext=NULL;
pWaveHdr1->reserved=0;
waveInPrepareHeader(hWaveIn,pWaveHdr1,sizeof(WAVEHDR));
pWaveHdr2->lpData=(LPTSTR)pBuffer2;
pWaveHdr2->dwBufferLength=INP_BUFFER_SIZE;
pWaveHdr2->dwBytesRecorded=0;
pWaveHdr2->dwUser=0;
pWaveHdr2->dwFlags=0;
pWaveHdr2->dwLoops=1;
pWaveHdr2->lpNext=NULL;
pWaveHdr2->reserved=0;
waveInPrepareHeader(hWaveIn,pWaveHdr2,sizeof(WAVEHDR));
//////////////////////////////////////////////////////////////////////////
pSaveBuffer = (PBYTE)realloc (pSaveBuffer, 1) ;
// Add the buffers
waveInAddBuffer (hWaveIn, pWaveHdr1, sizeof (WAVEHDR)) ;
waveInAddBuffer (hWaveIn, pWaveHdr2, sizeof (WAVEHDR)) ;
3. 操作采集的音频数据
在WAVEIN中有如下几个消息
MM_WOM_OPEN //设备的打开
MM_WIM_DATA //设备数据的采集及操作
MM_WIM_CLOSE //设备的关闭
void CRecordHWndDlg::OnMM_WIM_DATA(UINT wParam, LONG lParam)
{
// TODO: Add your message handler code here and/or call default
// Reallocate save buffer memory
//////////////////////////////////////////////////////////////////////////
pNewBuffer = (PBYTE)realloc (pSaveBuffer, dwDataLength +
((PWAVEHDR) lParam)->dwBytesRecorded) ;
if (pNewBuffer == NULL)
{
waveInClose (hWaveIn) ;
MessageBeep (MB_ICONEXCLAMATION) ;
AfxMessageBox("erro memory");
return ;
}
pSaveBuffer = pNewBuffer ;
//////////////////////////////////////////////////////////////////////////
CopyMemory (pSaveBuffer + dwDataLength, ((PWAVEHDR) lParam)->lpData,
((PWAVEHDR) lParam)->dwBytesRecorded) ;
dwDataLength += ((PWAVEHDR) lParam)->dwBytesRecorded ;
if (bEnding)
{
waveInClose (hWaveIn) ;
return ;
}
CFile file;
file.Open("data.txt",CFile::modeWrite|CFile::modeCreate);
file.Write(pSaveBuffer,dwDataLength);
file.Close();
// Send out a new buffer
waveInAddBuffer (hWaveIn, (PWAVEHDR) lParam, sizeof (WAVEHDR)) ;
TRACE("done input data\n");
return ;
}
本文地址:http://com.8s8s.com/it/it322.htm