C++获取Win10系统的音频设备
malong 发布于 2022-01-29

使用C++获取Win10系统上的音频设备,代码如下

#include "stdafx.h"
#include <windows.h>
#include <mmdeviceapi.h>
#include <wrl/client.h>
#include <memory>
#include <propkeydef.h>
#include <functiondiscoverykeys_devpkey.h>
#include <devicetopology.h>
#include <propsys.h>
#include <list>

using namespace std;

std::string unicode_utf8(const std::wstring & wstr)
{
	int ansiiLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
	char *pAssii = (char*)malloc(sizeof(char)*ansiiLen);
	WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pAssii, ansiiLen, nullptr, nullptr);
	std::string ret_str = pAssii;
	free(pAssii);
	return ret_str;
}

std::wstring ascii_unicode(const std::string & str)
{
	int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);

	wchar_t *pUnicode = (wchar_t*)malloc(sizeof(wchar_t)*unicodeLen);

	MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, unicodeLen);

	std::wstring ret_str = pUnicode;

	free(pUnicode);

	return ret_str;
}

int main(){

	Microsoft::WRL::ComPtr<IMMDeviceEnumerator> device_enumerator = nullptr;
	Microsoft::WRL::ComPtr<IMMDevice> device = nullptr;
	Microsoft::WRL::ComPtr<IMMDeviceCollection> collection = nullptr;

	LPWSTR current_device_id = NULL;

	bool input = false;

	list<string> devices;

	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	do {

		HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)device_enumerator.GetAddressOf());

		if (FAILED(hr)) {
			break;
		}

		hr = device_enumerator->GetDefaultAudioEndpoint(input == true ? eCapture : eRender, eConsole, device.GetAddressOf());

		if (FAILED(hr)) {
			break;
		}

		hr = device_enumerator->EnumAudioEndpoints(input == true ? eCapture : eRender, DEVICE_STATE_ACTIVE, collection.GetAddressOf());

		if (FAILED(hr)) {
			break;
		}

		UINT count;
		hr = collection->GetCount(&count);

		if (FAILED(hr)) {
			break;
		}

		hr = device->GetId(&current_device_id);

		if (FAILED(hr)) {
			break;
		}

		//std::string id = utils_string::unicode_utf8(current_device_id);

		CoTaskMemFree(current_device_id);

		IPropertyStore *pPropertyStore = NULL;
		PROPVARIANT pv;
		PropVariantInit(&pv);

		hr = device->OpenPropertyStore(STGM_READ, &pPropertyStore);
		if (FAILED(hr)) {
			break;
		}

		hr = pPropertyStore->GetValue(PKEY_Device_FriendlyName, &pv);
		if (FAILED(hr)) {
			//ret = AE_CO_GET_VALUE_FAILED;
			break;
		}

		if (pv.vt == VT_LPWSTR) {
			string name = unicode_utf8(pv.pwszVal);
			devices.push_back(name);
		}
		else if (pv.vt == VT_LPSTR) {
			string name = unicode_utf8(ascii_unicode(pv.pszVal));
			devices.push_back(name);
		}

		PropVariantClear(&pv);
	} while (0);

	system("pause");
	return 0;
}
malong
关注 私信
文章
35
关注
0
粉丝
0