參考:https://msdn.microsoft.com/en-us/library/windows/desktop/dd316551%28v=vs.85%29.aspxwindows
因爲一個我的需求須要抓取聲卡音頻數據,可是找了一圈好像都是麥克風錄音的,而後發現Potplayer裏面的聲音抓取用wasapi,因而就找了了微軟這個msdn文檔,根據例子看起來很簡單。直接上我修改後的代碼。api
依賴頭文件及庫:ui
#include <mmdeviceapi.h>
#include <Audioclient.h>
#include <Functiondiscoverykeys_devpkey.h>code
-lole32 -lmmdevapiorm
請先初始化com庫,CoInitializeEx( NULL, COINIT_MULTITHREADED );文檔
IMMDeviceEnumerator *pEnumerator = NULL; IMMDevice *pEndpoint = NULL; IAudioClient* pAudioClient = NULL; IAudioCaptureClient* pAudioCaptureClient = NULL; WAVEFORMATEX* pwfx = NULL; pEnumerator->GetDefaultAudioEndpoint(eRender,eConsole,&pEndpoint); HRESULT hr = pEndpoint->Activate(__uuidof(IAudioClient),CLSCTX_ALL,NULL,(void**)&pAudioClient); hr = pAudioClient->GetMixFormat(&pwfx); hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, pwfx, NULL); hr = pAudioClient->GetService(__uuidof(IAudioCaptureClient),(void**)&pAudioCaptureClient); pAudioClient->Start(); for(;;) { uchar* data = NULL; uint packetLength = 0,numFramesAvailable = 0; ulong flags; hr = pAudioCaptureClient->GetNextPacketSize(&packetLength); if(packetLength == 0) { Sleep(1); continue; } hr = pAudioCaptureClient->GetBuffer( &data, &numFramesAvailable, &flags, NULL, NULL); if (flags & AUDCLNT_BUFFERFLAGS_SILENT) { data = NULL; } if(data != NULL) { //這裏data就是捕獲到的pcm數據,大小爲numFramesAvailable*pwfx->nBlockAlign //注意pcm的格式,在我電腦上是signed float 32bit } pAudioCaptureClient->ReleaseBuffer(numFramesAvailable); }