C++ 修改Windows系统音量

该代码示例展示了如何使用WindowsAPI获取默认音频设备,获取音量控制接口,并进行音量设置和查询。通过SetWinSound类,可以实现设置和获取系统音量的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:前面的全局函数如果报错加内联 inline,我在ue c++中测试过

测试:创建SetWinSound 对象,调用函数即可

代码如下:

.h

#include <iostream>
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>



 // 获取默认音频设备
IMMDevice* GetDefaultAudioDevice()
{
    IMMDeviceEnumerator* deviceEnumerator = NULL;
    HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
        __uuidof(IMMDeviceEnumerator), (LPVOID*)&deviceEnumerator);
    if (FAILED(hr))
    {
        return NULL;
    }
    IMMDevice* defaultDevice = NULL;
    hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
    deviceEnumerator->Release();
    if (FAILED(hr))
    {
        return NULL;
    }
    return defaultDevice;
}

// 获取音量控制接口
IAudioEndpointVolume* GetAudioEndpointVolume(IMMDevice* device)
{
    IAudioEndpointVolume* endpointVolume = NULL;
    HRESULT hr = device->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER,
        NULL, (LPVOID*)&endpointVolume);
    if (FAILED(hr))
    {
        return NULL;
    }
    return endpointVolume;
}

// 获取当前音量(0-100)
int GetCurrentVolume(IAudioEndpointVolume* endpointVolume)
{
    float currentVolume = 0.0f; // 0.0 - 1.0
    HRESULT hr = endpointVolume->GetMasterVolumeLevelScalar(&currentVolume);
    if (FAILED(hr))
    {
        return -1;
    }
    return int(currentVolume * 100); // convert to percentage
}

// 设置音量(0-100)
void SetCurrentVolume(IAudioEndpointVolume* endpointVolume, int volume)
{
    float newVolume = volume / 100.0f; // convert to scalar
    HRESULT hr = endpointVolume->SetMasterVolumeLevelScalar(newVolume, NULL);
}

class   SetWinSound
{
public:
    SetWinSound();
public:
    IMMDevice* device;
    IAudioEndpointVolume* endpointVolume;

    //设置音量大小
    int new_volume = 50;

    //设置系统声音
    int SetWindowsSound(int new_volume);
    //设置当前声音
    int GetWindowsSound();
};

.cpp

#include "SetWinSound.h"

SetWinSound::SetWinSound()
{
    CoInitializeEx(NULL, COINIT_MULTITHREADED); // initialize COM library

     device = GetDefaultAudioDevice(); // get default audio device

     endpointVolume = GetAudioEndpointVolume(device); // get audio endpoint volume interface
    
}

int SetWinSound::SetWindowsSound(int new_volume1)
{
    SetCurrentVolume(endpointVolume, new_volume1);

    endpointVolume->Release(); // release resources
    device->Release();
    CoUninitialize();

    return 0;
}
int SetWinSound::GetWindowsSound()
{
    GetCurrentVolume(endpointVolume);
    endpointVolume->Release(); // release resources
    device->Release();
    CoUninitialize();
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值