Search code examples
c++winapihresult

How to Initialize HRESULT for SetMasterVolume?


#include <iostream>
#include <windows.h>
#include <Audioclient.h>

int main(){
    ShellExecute(NULL, "open", "https://www.youtube.com/watch?v=zf2VYAtqRe0", NULL, NULL, SW_SHOWNORMAL);
    HRESULT SetMasterVolume(1.0, NULL);
    return();
}

Okay so I'm trying to code this program, that opens a YouTube song, and turns up the volume at the same time. I don´t understand the error I get.

ERROR : C2440 ´initializing´: cannot convert from ´initializer list´ to ´HRESULT´

So therefore my question is: how do I initialize HRESULT so SetMasterVolume works? Or, how to setup SetMasterVolume? And please, if possible, explain why I cant just write

SetMasterVolume(1.0,NULL);

When I have included audioclient.h


Solution

  • ISimpleAudioVolume::SetMasterVolume is a COM method, it is not a regular WinAPI. You get a compile error when you just type in the function. Adding HRESULT in front of it will cause a different C++ error.

    Use this code instead, with SetMasterVolumeLevelScalar

    Based on code from:
    Change Master Volume in Visual C++

    #include <Windows.h>
    #include <Mmdeviceapi.h>
    #include <Endpointvolume.h>
    
    BOOL ChangeVolume(float nVolume)
    {
        HRESULT hr = NULL;
        IMMDeviceEnumerator *deviceEnumerator = NULL;
        hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
            __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator);
        if(FAILED(hr))
            return FALSE;
    
        IMMDevice *defaultDevice = NULL;
        hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
        deviceEnumerator->Release();
        if(FAILED(hr))
            return FALSE;
    
        IAudioEndpointVolume *endpointVolume = NULL;
        hr = defaultDevice->Activate(__uuidof(IAudioEndpointVolume),
            CLSCTX_INPROC_SERVER, NULL, (LPVOID *)&endpointVolume);
        defaultDevice->Release();
        if(FAILED(hr))
            return FALSE;
    
        hr = endpointVolume->SetMasterVolumeLevelScalar(nVolume, NULL);
        endpointVolume->Release();
    
        return SUCCEEDED(hr);
    }
    
    int main()
    {
        CoInitialize(NULL);
        ChangeVolume(0.5);
        CoUninitialize();
        return 0;
    }