C++ 採集音頻PCM流功能

#include "stdafx.h"  
#include <stdio.h>    
#include <Windows.h>    
#pragma comment(lib, "winmm.lib")    
  
HWAVEIN hWaveIn;  //輸入設備  
WAVEFORMATEX waveform; //採集音頻的格式,結構體  
BYTE *pBuffer1;//採集音頻時的數據緩存  
WAVEHDR wHdr1; //採集音頻時包含數據緩存的結構體  
FILE *pf;  
int _tmain(int argc, _TCHAR* argv[])  
{  
    HANDLE          wait;  
    waveform.wFormatTag = WAVE_FORMAT_PCM;//聲音格式爲PCM  
    waveform.nSamplesPerSec = 8000;//採樣率,16000次/秒  
    waveform.wBitsPerSample = 16;//採樣比特,16bits/次  
    waveform.nChannels = 1;//採樣聲道數,2聲道  
    waveform.nAvgBytesPerSec = 16000;//每秒的數據率,就是每秒能採集多少字節的數據  
    waveform.nBlockAlign = 2;//一個塊的大小,採樣bit的字節數乘以聲道數  
    waveform.cbSize = 0;//通常爲0  
  
    wait = CreateEvent(NULL, 0, 0, NULL);  
    //使用waveInOpen函數開啓音頻採集  
    waveInOpen(&hWaveIn, WAVE_MAPPER, &waveform,(DWORD_PTR)wait, 0L, CALLBACK_EVENT);  
  
    //創建兩個數組(這裏能夠創建多個數組)用來緩衝音頻數據  
    DWORD bufsize = 1024*100;//每次開闢10k的緩存存儲錄音數據  
    int i = 20;  
    fopen_s(&pf, "錄音測試.pcm", "wb");  
    while (i--)//錄製20左右秒聲音,結合音頻解碼和網絡傳輸能夠修改成實時錄音播放的機制以實現對講功能  
    {  
        pBuffer1 = new BYTE[bufsize];  
        wHdr1.lpData = (LPSTR)pBuffer1;  
        wHdr1.dwBufferLength = bufsize;  
        wHdr1.dwBytesRecorded = 0;  
        wHdr1.dwUser = 0;  
        wHdr1.dwFlags = 0;  
        wHdr1.dwLoops = 1;  
        waveInPrepareHeader(hWaveIn, &wHdr1, sizeof(WAVEHDR));//準備一個波形數據塊頭用於錄音  
        waveInAddBuffer(hWaveIn, &wHdr1, sizeof (WAVEHDR));//指定波形數據塊爲錄音輸入緩存  
        waveInStart(hWaveIn);//開始錄音  
        Sleep(1000);//等待聲音錄製1s  
        waveInReset(hWaveIn);//中止錄音  
        fwrite(pBuffer1, 1, wHdr1.dwBytesRecorded, pf);  
        delete pBuffer1;      
        printf("%ds  ", i);  
    }  
    fclose(pf);  
  
    waveInClose(hWaveIn);  
    return 0;  
}

另外,還有一篇:音頻操做所需頭文件和連接庫 帖子及相關代碼( https://www.cnblogs.com/lidabo/p/3701959.html )很不錯,做者的代碼我已下載到網盤 html

相關文章
相關標籤/搜索