获取音频设备,包括获取麦克风、扬声器设备。主要介绍获取设备列表以及默认设备。
技术简介
使用mmdeviceapi技术可以获取麦克风、扬声器设备
使用模块(库)
使用windows的mmdeviceapi库
主要流程和代码
获取默认设备
int AudioDevice::getDefaultDevice(bool isMic, std::string& id, std::string& name)
{
HELPER::ComUtil comUtil;
int err = ERROR_CODE_OK;
Microsoft::WRL::ComPtr<IMMDeviceEnumerator> deviceEnumerator = nullptr;
Microsoft::WRL::ComPtr<IMMDevice> endpointDevice = nullptr;
do {
HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator), (void**)deviceEnumerator.GetAddressOf());
if (FAILED(hr)) {
err = ERROR_CODE_COM_CREATE_INSTANCE_FAILED;
break;
}
EDataFlow dataFlow = isMic ? eCapture : eRender;
hr = deviceEnumerator->GetDefaultAudioEndpoint(dataFlow, eConsole, endpointDevice.GetAddressOf());
if (FAILED(hr)) {
err = ERROR_CODE_COM_GET_AUDIO_ENDPOINT_FAILED;
break;
}
LPWSTR currentDeviceId = nullptr;
hr = endpointDevice->GetId(¤tDeviceId);
if (FAILED(hr)) {
err = ERROR_CODE_COM_GET_ENDPOINT_ID_FAILED;
break;
}
std::string defaultDeviceId = HELPER::StringConverter::convertUnicodeToUtf8(currentDeviceId);
CoTaskMemFree(currentDeviceId