调节系统音量VC++ (win10/win7)

#include  
#include  
#include
#include




bool SetVolum(int volume)
{
HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator=0;
IMMDevice* pDevice=0;
IAudioEndpointVolume* pAudioEndpointVolume=0;
IAudioClient* pAudioClient=0;


try{
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),NULL,CLSCTX_ALL,__uuidof(IMMDeviceEnumerator),(void**)&pDeviceEnumerator);
if(FAILED(hr)) throw "CoCreateInstance";
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender,eMultimedia,&pDevice);
if(FAILED(hr)) throw "GetDefaultAudioEndpoint";
hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),CLSCTX_ALL,NULL,(void**)&pAudioEndpointVolume);
if(FAILED(hr)) throw "pDevice->Active";
hr = pDevice->Activate(__uuidof(IAudioClient),CLSCTX_ALL,NULL,(void**)&pAudioClient);
if(FAILED(hr)) throw "pDevice->Active";


float fVolume;
fVolume = level/100.0f;
hr = pAudioEndpointVolume->SetMasterVolumeLevelScalar(fVolume,&GUID_NULL);
if(FAILED(hr)) throw "SetMasterVolumeLevelScalar";


pAudioClient->Release();
pAudioEndpointVolume->Release();
pDevice->Release();
pDeviceEnumerator->Release();
return true;
}

catch(...){
if(pAudioClient) pAudioClient->Release();
if(pAudioEndpointVolume) pAudioEndpointVolume->Release();
if(pDevice) pDevice->Release();
if(pDeviceEnumerator) pDeviceEnumerator->Release();
throw;
}
return false;
}


int   GetVolume()
{



HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator=0;
IMMDevice* pDevice=0;
IAudioEndpointVolume* pAudioEndpointVolume=0;
IAudioClient* pAudioClient=0;


try{
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),NULL,CLSCTX_ALL,__uuidof(IMMDeviceEnumerator),(void**)&pDeviceEnumerator);
if(FAILED(hr)) throw "CoCreateInstance";
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender,eMultimedia,&pDevice);
if(FAILED(hr)) throw "GetDefaultAudioEndpoint";
hr = pDevice->Activate(__uuidof(IAudioEndpointVolume),CLSCTX_ALL,NULL,(void**)&pAudioEndpointVolume);
if(FAILED(hr)) throw "pDevice->Active";
hr = pDevice->Activate(__uuidof(IAudioClient),CLSCTX_ALL,NULL,(void**)&pAudioClient);
if(FAILED(hr)) throw "pDevice->Active";


float fVolume;


hr = pAudioEndpointVolume->GetMasterVolumeLevelScalar(&fVolume);

if(FAILED(hr)) throw "SetMasterVolumeLevelScalar";


pAudioClient->Release();
pAudioEndpointVolume->Release();
pDevice->Release();
pDeviceEnumerator->Release();


int  intVolume = fVolume*100+1; 
if(fVolume>100)
{
fVolume =100;
}


}


catch(...){
if(pAudioClient) pAudioClient->Release();
if(pAudioEndpointVolume) pAudioEndpointVolume->Release();
if(pDevice) pDevice->Release();
if(pDeviceEnumerator) pDeviceEnumerator->Release();
throw;
}

}



call :

CoInitialize(0);
nVolume =GetVolume();
CoUninitialize();


CoInitialize(0);
nVolume =SetVolum( 0-----100);
CoUninitialize();




你可能感兴趣的:(MutilMedia)