#include <AudioClient.h>
#include <audiopolicy.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#define Release_Com_Obj(obj) if ((obj)) (obj)->Release();
#define Check_HR_Break(hr, str) if ((hr) != S_OK)\
{\
printf((str));\
break;\
}
// 设置程序自身音量,范围 0-1.0。与 C:\Windows\System32\sndvol.exe 一致
void TestSimpleAudioVolume(int iNum)
{
HRESULT hr = CoInitialize(nullptr);
if (FAILED(hr))
{
CoUninitialize();
return;
}
IAudioClient* pAudioClient = NULL;
IMMDeviceEnumerator* pDeviceEnumerator = NULL;
IMMDevice* pDevice = NULL;
ISimpleAudioVolume* pVolume = NULL;
do
{
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pDeviceEnumerator);
Check_HR_Break(hr, "CoCreateInstance Failed\n");
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
Check_HR_Break(hr, "GetDefaultAudioEndpoint Failed\n");
hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&pAudioClient);
Check_HR_Break(hr, "Activate Failed\n");
float fVolumeLevel = 0;
REFERENCE_TIME hnsRequestedDuration = 100;
WAVEFORMATEX* pwfx = NULL;
hr = pAudioClient->GetMixFormat(&pwfx);
Check_HR_Break(hr, "GetMixFormat Failed\n");
hr = pAudioClient->Initialize(
AUDCLNT_SHAREMODE_SHARED,
0,
hnsRequestedDuration,
0,
pwfx,
NULL);
Check_HR_Break(hr, "Initialize Failed\n");
hr = pAudioClient->GetService(__uuidof(ISimpleAudioVolume), (void**)&pVolume);
Check_HR_Break(hr, "GetService Failed\n");
hr = pVolume->GetMasterVolume(&fVolumeLevel);
Check_HR_Break(hr, "GetMasterVolume Failed\n");
printf("GetMasterVolume level = %f\n", fVolumeLevel);
hr = pVolume->SetMasterVolume(iNum / 100.0f, NULL);
Check_HR_Break(hr, "SetMasterVolume Failed\n");
hr = pVolume->GetMasterVolume(&fVolumeLevel);
Check_HR_Break(hr, "GetMasterVolume Failed\n");
printf("GetMasterVolume level = %f\n", fVolumeLevel);
printf("\n");
} while (0);
Release_Com_Obj(pAudioClient);
Release_Com_Obj(pDeviceEnumerator);
Release_Com_Obj(pDevice);
Release_Com_Obj(pVolume);
CoUninitialize();
}
#pragma comment(lib,"winmm.lib")
int main()
{
//Test();
TestSimpleAudioVolume(100);
mciSendString(TEXT("open E:\\CloudMusic\\111.mp3 alias shanv"), NULL, 0, NULL);
mciSendString(TEXT("play shanv"), NULL, 0, NULL);
for (int index = 100; index > 0;)
{
Sleep(2000);
TestSimpleAudioVolume(index);
index -= 5;
}
mciSendString(TEXT("stop movie"), NULL, 0, NULL);
system("pause");
return 0;
}