Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

winapi - Programmatically switch audio devices on Windows 7

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 input devices.

I find myself having to switch between them fairly frequently. At the moment this is a manual process: right-click on the speaker icon, choose one of "Playback devices" or "Recording devices", choose the correct device in the list (and there's some "dead" ones in there, too) and then hit "Set Default".

I've looked around, and all I can find are people scripting SendKeys to automate this.

That sucks.

Is there anyway to programmatically switch audio input/output devices, so that I can write a simple tray app/hotkey app to make this easier?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...