Core Audio API控制windows音量 C++
開發環境
-VS 2019
-windows 10 企業版 2016 長期服務版
-其他環境沒有測試過
示例代碼:
test.h
#pragma once
#include "SystemVolume.h"
#include <iostream>
#ifndef SRC_DEMO_H
#define SRC_DEMO_H
extern "C"
{
}
#endif
test.cpp
#include "test.h"
using namespace std;
using namespace SystemConf;
int main() {
SystemVolume systemVolume;
try {
cout << "初始化 CoreAudioAPI " << endl;
systemVolume.init();
int volume = systemVolume.getVolume();
cout << "獲取當前音量爲:" << volume << endl;
cout << "設置音量爲:80" << endl;
systemVolume.setVolume(80);
volume = systemVolume.getVolume();
cout << "獲取當前音量爲:" << volume << endl;
cout << "關閉服務" << endl;
systemVolume.close();
}catch (string e) {
cout << e << endl;
}catch (...) {
cout << "出現異常,關閉服務 釋放資源" << endl;
systemVolume.close();
}
return 0;
}
SystemVolume.h
#pragma once
#ifndef _SystemVolume_h_
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <audioclient.h>
#define _SystemVolume_h_
namespace SystemConf {
class SystemVolume {
private:
HRESULT hr;
IMMDeviceEnumerator* pDeviceEnumerator = 0;
IMMDevice* pDevice = 0;
IAudioEndpointVolume* pAudioEndpointVolume = 0;
IAudioClient* pAudioClient = 0;
public:
/**初始化服務*/
void init();
/**關閉服務 釋放資源*/
void close();
/**設置音量*/
void setVolume(int volume);
/**獲取系統音量*/
int getVolume();
/**靜音*/
void Mute();
/**解除靜音*/
void UnMute();
};
}
#endif
SystemVolume.cpp
#include "SystemVolume.h"
namespace SystemConf {
void SystemVolume::init() {
hr = CoInitialize(0);
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pDeviceEnumerator);
if (FAILED(hr)) throw "InitException:pDeviceEnumerator is NULL;";
hr = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
if (FAILED(hr)) throw "InitException:pDevice is NULL";
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";
}
void SystemVolume::close() {
if (pAudioClient) pAudioClient->Release();
if (pAudioEndpointVolume) pAudioEndpointVolume->Release();
if (pDevice) pDevice->Release();
if (pDeviceEnumerator) pDeviceEnumerator->Release();
CoUninitialize();
}
void SystemVolume::setVolume(int volume) {
float fVolume = volume / 100.0f;
hr = pAudioEndpointVolume->SetMasterVolumeLevelScalar(fVolume, &GUID_NULL);
if (FAILED(hr)) throw "SetMasterVolumeLevelScalar";
}
int SystemVolume::getVolume() {
float volume;
hr = pAudioEndpointVolume->GetMasterVolumeLevelScalar(&volume);
if (FAILED(hr)) throw "getVolume() throw Exception";
return (int)round(volume*100.0);
}
void SystemVolume::Mute() {
hr = pAudioEndpointVolume->SetMute(TRUE, NULL);
if (FAILED(hr)) throw "Mute() throw Exception";
}
void SystemVolume::UnMute() {
hr = pAudioEndpointVolume->SetMute(FALSE, NULL);
if (FAILED(hr)) throw "UnMute() throw Exception";
}
}
效果展示