60 lines
1.7 KiB
C++
Raw Normal View History

2024-11-25 17:15:44 +08:00
#include "SoundController.h"
#include <mmdeviceapi.h>
#include <endpointvolume.h>
#include <QDebug>
SoundController::SoundController(QObject *parent) : QObject(parent)
{
HRESULT hr = CoInitialize(NULL);
if (FAILED(hr)) {
qDebug() << "Failed to initialize COM";
return;
}
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&deviceEnumerator);
if (FAILED(hr)) {
qDebug() << "Failed to create the device enumerator";
CoUninitialize();
return;
}
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &device);
if (FAILED(hr)) {
qDebug() << "Failed to get the default audio endpoint";
deviceEnumerator->Release();
CoUninitialize();
return;
}
hr = device->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, (void**)&endpointVolume);
if (FAILED(hr)) {
qDebug() << "Failed to activate the endpoint volume interface";
device->Release();
deviceEnumerator->Release();
CoUninitialize();
return;
}
}
int SoundController::getSystemVolume()
{
float fVolume;
HRESULT hr = endpointVolume->GetMasterVolumeLevelScalar(&fVolume);
if (FAILED(hr)) {
qDebug() << "Failed to get the current volume";
return -1;
}
return static_cast<int>(fVolume * 100);
}
bool SoundController::setSystemVolume(int volume)
{
float fVolume = static_cast<float>(volume) / 100.0f;
HRESULT hr = endpointVolume->SetMasterVolumeLevelScalar(fVolume, NULL);
if (FAILED(hr)) {
qDebug() << "Failed to set the volume";
return false;
}
return true;
}