我可以使用IAudioEndpointVolume
和SetMasterVolumeLevel()
方法以编程方式通过C++在Windows上更改默认声音设备的音量级别。
在带有多个声卡的PC上,如何更改非默认声音设备的音量级别?
最佳答案
我解决了,这是我的代码:
HRESULT hr = S_OK;
IMMDeviceEnumerator *pEnumerator = NULL;
IMMDeviceCollection *pCollection = NULL;
IMMDevice *pEndpoint = NULL;
IPropertyStore *pProps = NULL;
LPWSTR pwszID = NULL;
CoInitialize(NULL);
hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL,CLSCTX_ALL, IID_IMMDeviceEnumerator,(void**)&pEnumerator);
hr = pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE,&pCollection); // ** use "eCapture" for microphones and "eRender" for speakers.
hr = pCollection->GetCount(&count);
if (count == 0){
cout <<"No endpoints found."<<endl;
}
for (ULONG i = 0; i < count; i++){
hr = pCollection->Item(i, &pEndpoint);
hr = pEndpoint->GetId(&pwszID);
IAudioEndpointVolume *endpointVolume = NULL;
pEnumerator->GetDevice(pwszID,&pEndpoint);
pEndpoint->Activate(__uuidof(IAudioEndpointVolume),CLSCTX_INPROC_SERVER, NULL, (LPVOID *)&endpointVolume);
hr = pEndpoint->OpenPropertyStore(STGM_READ, &pProps);
PROPVARIANT varName;
PropVariantInit(&varName);
hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
printf("Endpoint %d: \"%S\" (%S)\n",i, varName.pwszVal, pwszID);
CoTaskMemFree(pwszID);
pwszID = NULL;
PropVariantClear(&varName);
endpointVolume->SetMasterVolumeLevelScalar(0.1, NULL); // set volume level of device to 0.1 (10%)
// endpointVolume->Release();
//you can save endpointVolume in a container to set set volume level for each device.
}