编程调节Win7/Win8系统音量的一种方法

不得不说, 自Win7(好像是吧), Windows的音量调节功能比以前更人性化了....
     但编程接口却变得更加复杂了............. 还要用到IAudioEndpointVolume………….

下面的代码是我整理的, 经测试可用, 嫌麻烦的可以直接拿来用, 接口很简单, 因而只能整个系统的音量...

#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <audioclient.h> //参数:
// -2 恢复静音
// -1 静音
// 0~100:音量比例
bool SetVolumeLevel(int level)
{
HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator=;
IMMDevice* pDevice=;
IAudioEndpointVolume* pAudioEndpointVolume=;
IAudioClient* pAudioClient=; 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"; if(level==-){
hr = pAudioEndpointVolume->SetMute(FALSE,NULL);
if(FAILED(hr)) throw "SetMute";
}else if(level==-){
hr = pAudioEndpointVolume->SetMute(TRUE,NULL);
if(FAILED(hr)) throw "SetMute";
}else{
if(level< || level>){
hr = E_INVALIDARG;
throw "Invalid Arg";
} 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 main()
{
CoInitialize();
try{
//3秒后静音
Sleep();
SetVolumeLevel(-);
//3秒后恢复静音
Sleep();
SetVolumeLevel(-);
//调节音量
Sleep();
SetVolumeLevel();
Sleep();
SetVolumeLevel();
Sleep();
SetVolumeLevel();
}
catch(...){
//错误处理...
}
CoUninitialize();
return ;
}

下载:http://share.weiyun.com/19003dc8fd0804aaf1fc03b2430e832e

参考:
              IAudioEndpointVolume interface

Win7/Vista Audio API Master Volume Control

女孩不哭 @ cnblogs.com/memset @ 2014-04-07

上一篇:luoguP2826 LJJ的数学课


下一篇:H5 基于Web Storage 的客户端留言板