#include "stdafx.h"
#include <dshow.h>
#include <iostream>
#pragma comment(lib, "strmiids.lib")
void ListAudioDevices() {
ICreateDevEnum* pDevEnum = nullptr;
IEnumMoniker* pEnum = nullptr;
CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum));
pDevEnum->CreateClassEnumerator(CLSID_AudioInputDeviceCategory, &pEnum, 0);
if (!pEnum) {
std::cout << "没有找到音频输入设备" << std::endl;
return;
}
IMoniker* pMoniker = nullptr;
while (pEnum->Next(1, &pMoniker, nullptr) == S_OK) {
IPropertyBag* pPropBag;
pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
VARIANT varName;
VariantInit(&varName);
pPropBag->Read(L"FriendlyName", &varName, 0);
std::wcout << L"设备名称: " << varName.bstrVal << std::endl;
VariantClear(&varName);
pPropBag->Release();
pMoniker->Release();
}
pEnum->Release();
pDevEnum->Release();
}
void CaptureAndPlayAudio(const wchar_t* deviceName) {
IGraphBuilder* pGraph = nullptr;
ICaptureGraphBuilder2* pCaptureBuilder = nullptr;
ICreateDevEnum* pDevEnum = nullptr;
IEnumMoniker* pEnum = nullptr;
IMoniker* pMoniker = nullptr;
// 创建Graph Builder和Capture Graph Builder
CoCreateInstance(CLSID_FilterGraph, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pGraph));
CoCreateInstance(CLSID_CaptureGraphBuilder2, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pCaptureBuilder));
pCaptureBuilder->SetFiltergraph(pGraph);
// 创建设备枚举器并获取音频输入设备
CoCreateInstance(CLSID_SystemDeviceEnum, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum));
pDevEnum->CreateClassEnumerator(CLSID_AudioInputDeviceCategory, &pEnum, 0);
// 查找特定设备
while (pEnum->Next(1, &pMoniker, nullptr) == S_OK) {
IPropertyBag* pPropBag;
pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
VARIANT varName;
VariantInit(&varName);
pPropBag->Read(L"FriendlyName", &varName, 0);
if (wcscmp(varName.bstrVal, deviceName) == 0)
{
IBaseFilter* pAudioInputFilter;
pMoniker->BindToObject(0, 0, IID_PPV_ARGS(&pAudioInputFilter));
pGraph->AddFilter(pAudioInputFilter, L"Audio Capture");
// 渲染音频流到系统默认音频输出设备
pCaptureBuilder->RenderStream(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Audio, pAudioInputFilter, nullptr, nullptr);
// 启动图表
IMediaControl* pMediaControl;
pGraph->QueryInterface(IID_PPV_ARGS(&pMediaControl));
pMediaControl->Run();
std::wcout << L"正在捕获和播放音频... 按Enter停止。" << std::endl;
std::cin.get(); // 等待按下Enter停止
// 停止并释放资源
pMediaControl->Stop();
pMediaControl->Release();
pAudioInputFilter->Release();
break;
}
VariantClear(&varName);
pPropBag->Release();
pMoniker->Release();
}
// 释放资源
pEnum->Release();
pDevEnum->Release();
pGraph->Release();
pCaptureBuilder->Release();
}
int main() {
// 初始化COM库
CoInitialize(nullptr);
// 列出可用设备
ListAudioDevices();
// 设备名称
const wchar_t* deviceName = L"数字音频接口 (0.5)";
// 捕获并播放音频
CaptureAndPlayAudio(deviceName);
// 释放COM库
CoUninitialize();
return 0;
}