2019独角兽企业重金招聘Python工程师标准>>>
参考:https://msdn.microsoft.com/en-us/library/windows/desktop/dd316551%28v=vs.85%29.aspx
由于一个个人需求需要抓取声卡音频数据,但是找了一圈好像都是麦克风录音的,然后发现Potplayer里面的声音抓取用wasapi,于是就找了了微软这个msdn文档,根据例子看起来很简单。直接上我修改后的代码。
依赖头文件及库:
#include
#include
#include
-lole32 -lmmdevapi
请先初始化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);
}