Programmatically switch audio devices on Windows 7

前端 未结 2 881
予麋鹿
予麋鹿 2020-12-08 17:26

On my Windows 7 PC, I\'ve got a set of speakers, some wireless headphones and a USB web cam. This means that I have two possible audio output devices and 2 possible audio in

相关标签:
2条回答
  • 2020-12-08 18:19

    If you are looking into changing default devices programmatically, then this is impossible by design.

    • Programatically setting the default playback device (and recording device)
    • How to change default sound playback device programatically?
    0 讨论(0)
  • 2020-12-08 18:21

    Allegedly undocumented COM-interface IPolicyConfig (kudos to @author EreTIk) allows to do that.

    This is a sample implementation.

    HRESULT SetDefaultAudioPlaybackDevice(LPCWSTR devID)
    {
        IPolicyConfigVista *pPolicyConfig;
        ERole reserved = eConsole;
    
        HRESULT hr = CoCreateInstance(
                        __uuidof(CPolicyConfigVistaClient),
                        NULL, 
                        CLSCTX_ALL, 
                        __uuidof(IPolicyConfigVista), 
                        (LPVOID *)&pPolicyConfig);
    
        if (SUCCEEDED(hr))
        {
            hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
            pPolicyConfig->Release();
        }
    
        return hr;
    }
    

    A string of Device ID needs to be passed to this function. An example of a device id

    {0.0.1.00000000}.{d915c7bb-d5d7-4c92-80d9-1a0ee5d954f1}
    

    This device id can be obtained through audio device enumeration.

    0 讨论(0)
提交回复
热议问题