Change audio output Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
noname6500
Posts: 18
Joined: 29 Oct 2021, 04:07

Re: Change audio output

30 Nov 2021, 09:40

IVWidth wrote:
28 Nov 2021, 19:29
The code(s) shown in earlier posts show the use of two hotkeys. If it were me, since the toggle command doesn't mesh well with my brain for some reason, I would just include a hotkey reassignment in my hotkey command.

So pressing the hotkey once switches audio AND changes the hotkey assignment, then doing it again switches it back.
Using two hotkey is a solution and what I first used when I discovered this thread.
But I like the toggle method because it's more efficient (with limited hotkey space)

The toggle method I use relies on If s that check the "toggle" variable if its 0 or 1. The audiotoggle := !audiotoggle is a NOT. It changes the value from 0 to 1 and vice versa.

UPDATE:
I managed to edit the script where I only need one press for the first switch via running the script a few times at startup (simulating the multiple button press).
But this only works for one starting audio output.
WindyGhost69
Posts: 2
Joined: 19 Feb 2022, 09:54

Re: Change audio output

19 Feb 2022, 10:03

So i found an easiest way to change audio device without using the looooooong script made by others in this post.
Follow these easy steps:
Step 1: Download Nircmd and extract it to somewhere you won't delete is accidentally.
Step 2: Make or edit your existing ahk script with the following

Code: Select all

#F11::RUN "D:\location\to\nircmd.exe" setdefaultsounddevice Headphones
Return

#F12::RUN "D:\location\to\nircmd.exe" setdefaultsounddevice Speakers
Return
Here i have used Win+F11/Win+F12 , you can choose any hotkey.
RussF
Posts: 1311
Joined: 05 Aug 2021, 06:36

Re: Change audio output

19 Feb 2022, 10:17

Great idea! My only caution is that while I fully believe all of the Nir products to be inherently safe (I have most of them on my systems), many antivirus programs will trigger on them and quarantine them. Almost weekly, our company antivirus system (Bitdefender) will quarantine one of the utilities (seemingly at random) and I will have to whitelist it.

YMMV.

Russ
User avatar
mikeyww
Posts: 27361
Joined: 09 Sep 2014, 18:38

Re: Change audio output

19 Feb 2022, 10:41

You could put all of the utilities into one directory (with or without subdirectories), and then whitelist the directory.
User avatar
flyingDman
Posts: 2846
Joined: 29 Sep 2013, 19:01

Re: Change audio output

19 Feb 2022, 13:19

WindyGhost69 wrote:
19 Feb 2022, 10:03
So i found an easiest way to change audio device without using the looooooong script made by others in this post.
I think most forum members are interested to know about native AHK solutions rather than third party solutions. I personally do not want to rely on third party programs if I can find a way to do it with AHK. When you leave comments out, @Flipeador 's script is less than 50 lines long. That's not looooooong...
14.3 & 1.3.7
WindyGhost69
Posts: 2
Joined: 19 Feb 2022, 09:54

Re: Change audio output

05 Mar 2022, 14:56

flyingDman wrote:
19 Feb 2022, 13:19
WindyGhost69 wrote:
19 Feb 2022, 10:03
So i found an easiest way to change audio device without using the looooooong script made by others in this post.
I think most forum members are interested to know about native AHK solutions rather than third party solutions. I personally do not want to rely on third party programs if I can find a way to do it with AHK. When you leave comments out, @Flipeador 's script is less than 50 lines long. That's not looooooong...
I found this so i thought I'd just post it if anyone's interested.
User avatar
mikeyww
Posts: 27361
Joined: 09 Sep 2014, 18:38

Re: Change audio output

05 Mar 2022, 18:29

It's a great quote.
rinze24
Posts: 4
Joined: 24 May 2022, 01:05

Re: Change audio output

29 May 2022, 10:14

@Flipeador

Is there a way to change for specific program / application using the dll?

currently im using nirsoft soundvolumetview to achieve this
IVWidth
Posts: 17
Joined: 14 Mar 2021, 13:58

Re: Change audio output

08 Aug 2022, 19:48

flyingDman wrote:
19 Feb 2022, 13:19
WindyGhost69 wrote:
19 Feb 2022, 10:03
So i found an easiest way to change audio device without using the looooooong script made by others in this post.
I think most forum members are interested to know about native AHK solutions rather than third party solutions. I personally do not want to rely on third party programs if I can find a way to do it with AHK. When you leave comments out, @Flipeador 's script is less than 50 lines long. That's not looooooong...
It’s true. Like for a systemwide push to talk (PTT), flawless 3rd party solution is MICSWITCH V1.0.235.0 but yes, I want an AHK solution that isn’t full of tab tab up down Nintendo secret squirrel code to do it. :)
Gewerd_Strauss
Posts: 26
Joined: 12 Nov 2020, 02:34

Re: Change audio output

25 Sep 2022, 11:49

Had a bit of an headache adjusting this to my needs, but I am now very happy with it. One question remains - can this be done for Audio-IN as well? So for changing mic-setups? If yes, how would I go about that?
IVWidth
Posts: 17
Joined: 14 Mar 2021, 13:58

Re: Change audio output

25 Sep 2022, 23:07

I imagine it would work I f you can find the input equivalent to IMMDeviceEnumerator and the correct names of your inputs.

Sadly I don’t know those codes. Let me know if you find one that works?
Gewerd_Strauss
Posts: 26
Joined: 12 Nov 2020, 02:34

Re: Change audio output

26 Sep 2022, 04:21

IVWidth wrote:
25 Sep 2022, 23:07
I imagine it would work I f you can find the input equivalent to IMMDeviceEnumerator and the correct names of your inputs.

Sadly I don’t know those codes. Let me know if you find one that works?
I was simply blind, this was answered already and I completely overread it while skimming this topic :P
Now all I have to do is figure out how to have both in the same script, e.g. what variables for the various DLLCalls I can rename to ensure that I don't accidentally mix in and outputs, and which ones I cannot.
Gewerd_Strauss
Posts: 26
Joined: 12 Nov 2020, 02:34

Re: Change audio output

26 Sep 2022, 07:57

I have an additional question: (How) Can I retrieve the currently active audio in/audio out device's name? I need it to toggle off its respective GUI-button when the script starts.
patel8786
Posts: 4
Joined: 16 Jan 2019, 02:51

Re: Change audio output

19 Apr 2023, 16:26

WindyGhost69 wrote:
19 Feb 2022, 10:03
So i found an easiest way to change audio device without using the looooooong script made by others in this post.
Follow these easy steps:
Step 1: Download Nircmd and extract it to somewhere you won't delete is accidentally.
Step 2: Make or edit your existing ahk script with the following

Code: Select all

#F11::RUN "D:\location\to\nircmd.exe" setdefaultsounddevice Headphones
Return

#F12::RUN "D:\location\to\nircmd.exe" setdefaultsounddevice Speakers
Return
Here i have used Win+F11/Win+F12 , you can choose any hotkey.

Thanks so much

This got me on to a solution that allows you to toggle between 2 devices (using the same hotkey).
It's a bit more complicated but works well.

The same website that has Nircmd also has SoundVolumeView.
NB: you will need the device IDs. To get that, open the GUI SoundVolumeView.exe right click the device, select properties and copy item ID (should be something like this --> {0.0.0.00000000}.{f02546f1-643e-49e8-a8f2-46043fbc8962})

Also note this is an AHK v2 script, you can adapt it to v1

Code: Select all

; Switch Audio Device
; Windows key + s
$#s::
{
  Run("<***location***>\SoundVolumeView.exe /SwitchDefault `"<***Device ID For the first device***>`" `"{0.0.0.00000000}.{8274a21b-aabc-4a48-84c3-3ef50f85d191}`" all")
  return 
}
pplatinumss
Posts: 7
Joined: 08 Apr 2019, 16:40

Re: Change audio output

29 Apr 2023, 09:22

Did anyone ever fix the script for V2 latest?

I get

Code: Select all

Error: Missing ending "%"

Text:	% (Count)
Line:	22
File:	D:\Apps\AutoHotkey\scrips\Sound_Switch.F1.F2._q90a_2023.ahk

The program will exit.
Roboapple
Posts: 1
Joined: 11 Jun 2024, 23:23

Re: Change audio output

11 Jun 2024, 23:24

Flipeador wrote:
15 Mar 2021, 13:34
It works for me (W10 Pro 20H2 19042.867). Try this script with the latest version of AutoHotkey v2.

Code: Select all

#Requires AutoHotkey v2.0-a136-feda41f4
; http://www.daveamenta.com/2011-05/programmatically-or-command-line-change-the-default-sound-playback-device-in-windows-7/
; https://web.archive.org/web/20190317012739/http://www.daveamenta.com/2011-05/programmatically-or-command-line-change-the-default-sound-playback-device-in-windows-7/

List := EnumAudioEndpoints()

Devices := ""
for Device in List
    Devices .= Format("{} ({})`n`n", Device["Name"], Device["ID"])
MsgBox(Devices)

F6::
{
    SetDefaultEndpoint(GetDeviceID(List, "DENON-AVR (NVIDIA High Definition Audio)"))
    SetDefaultEndpoint(GetDeviceID(List, "Microphone (Yeti Stereo Microphone)"))
}

F7::
{
    SetDefaultEndpoint(GetDeviceID(List, "Headset Earphone (3- CORSAIR VOID ELITE Wireless Gaming Dongle)"))
    SetDefaultEndpoint(GetDeviceID(List, "Headset Microphone (3- CORSAIR VOID ELITE Wireless Gaming Dongle)"))
}

/*
    Generates a collection of audio endpoint devices that meet the specified criteria.
    Parameters:
        DataFlow:
            The data-flow direction for the endpoint devices in the collection.
            0   Audio rendering stream. Audio data flows from the application to the audio endpoint device, which renders the stream.
            1   Audio capture stream. Audio data flows from the audio endpoint device that captures the stream, to the application.
            2   Audio rendering or capture stream. Audio data can flow either from the application to the audio endpoint device, or from the audio endpoint device to the application.
        StateMask:
            The state or states of the endpoints that are to be included in the collection.
            1   Active. The audio adapter that connects to the endpoint device is present and enabled. In addition, if the endpoint device plugs into a jack on the adapter, then the endpoint device is plugged in.
            2   Disabled. The user has disabled the device in the Windows multimedia control panel (Mmsys.cpl).
            4   Not present. The audio adapter that connects to the endpoint device has been removed or disabled.
            8   Unplugged. The audio adapter that contains the jack for the endpoint device is present and enabled, but the endpoint device is not plugged into the jack. Only a device with jack-presence detection can be in this state.
    Return value:
        Returns an array of Map objects with the following keys:
        ID      Endpoint ID string that identifies the audio endpoint device.
        Name    The friendly name of the endpoint device.
*/
EnumAudioEndpoints(DataFlow := 2, StateMask := 1)
{
    List := []

    ; IMMDeviceEnumerator interface.
    ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nn-mmdeviceapi-immdeviceenumerator
    IMMDeviceEnumerator := ComObject("{BCDE0395-E52F-467C-8E3D-C4579291692E}", "{A95664D2-9614-4F35-A746-DE8DB63617E6}")

    ; IMMDeviceEnumerator::EnumAudioEndpoints method.
    ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdeviceenumerator-enumaudioendpoints
    ComCall(3, IMMDeviceEnumerator, "UInt", DataFlow, "UInt", StateMask, "UPtrP", &IMMDeviceCollection:=0)

    ; IMMDeviceCollection::GetCount method.
    ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-getcount
    ComCall(3, IMMDeviceCollection, "UIntP", &DevCount:=0)  ; Retrieves a count of the devices in the device collection.

    loop DevCount
    {
        List.Push(Device := Map())

        ; IMMDeviceCollection::Item method.
        ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevicecollection-item
        ComCall(4, IMMDeviceCollection, "UInt", A_Index-1, "UPtrP", &IMMDevice:=0)

        ; IMMDevice::GetId method.
        ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-getid
        ComCall(5, IMMDevice, "PtrP", &pBuffer:=0)
        Device["ID"] := StrGet(pBuffer)
        DllCall("Ole32.dll\CoTaskMemFree", "UPtr", pBuffer)

        ; MMDevice::OpenPropertyStore method.
        ; https://docs.microsoft.com/en-us/windows/win32/api/mmdeviceapi/nf-mmdeviceapi-immdevice-openpropertystore
        ComCall(4, IMMDevice, "UInt", 0x00000000, "UPtrP", &IPropertyStore:=0)

        Device["Name"] := GetDeviceProp(IPropertyStore, "{A45C254E-DF1C-4EFD-8020-67D146A850E0}", 14)

        ObjRelease(IPropertyStore)
        ObjRelease(IMMDevice)
    }

    ObjRelease(IMMDeviceCollection)

    return List
}

/*
    Set default audio render endpoint.
    Role:
        0x1   Default Device.
        0x2   Default Communication Device.
*/
SetDefaultEndpoint(DeviceID, Role := 3)
{
    ; Undocumented COM-interface IPolicyConfig.
    IPolicyConfig := ComObject("{870AF99C-171D-4F9E-AF0D-E63Df40c2BC9}", "{F8679F50-850A-41CF-9C72-430F290290C8}")
    if (Role & 0x1)
        ComCall(13, IPolicyConfig, "Str", DeviceID, "Int", 0)  ; Default Device
    if (Role & 0x2)
        ComCall(13, IPolicyConfig, "Str", DeviceID, "Int", 2)  ; Default Communication Device
}

/*
    Device Properties (Core Audio APIs)
    https://docs.microsoft.com/en-us/windows/win32/coreaudio/device-properties

    026E516E-B814-414B-83CD-856D6FEF4822, 2   The friendly name of the audio adapter to which the endpoint device is attached.
    A45C254E-DF1C-4EFD-8020-67D146A850E0, 2   The device description of the endpoint device.
    A45C254E-DF1C-4EFD-8020-67D146A850E0,14   The friendly name of the endpoint device.
*/
InitDeviceProp(clsid, n)
{
    clsid := CLSIDFromString(clsid, Buffer(16+4))
    NumPut("Int", n, clsid, 16)
    return clsid
}

GetDeviceProp(ptr, clsid, n)
{
    ; IPropertyStore::GetValue method.
    ; https://docs.microsoft.com/en-us/windows/win32/api/propsys/nf-propsys-ipropertystore-getvalue
    ComCall(5, ptr, "Ptr", InitDeviceProp(clsid, n), "Ptr", pvar := PropVariant())
    return String(pvar)
}

GetDeviceID(list, name)
{
    for device in list
        if InStr(device["Name"], name)
            return device["ID"]
    throw
}

CLSIDFromString(Str, Buffer := 0)
{
    if (!Buffer)
        Buffer := Buffer(16)
    DllCall("Ole32\CLSIDFromString", "Str", Str, "Ptr", Buffer, "HRESULT")
    return Buffer
}

class PropVariant
{
    __New()
    {
        this.buffer := Buffer(A_PtrSize == 4 ? 16 : 24)
        this.ptr    := this.buffer.ptr
        this.size   := this.buffer.size
    }

    __Delete()
    {
        DllCall("Ole32\PropVariantClear", "Ptr", this.ptr, "HRESULT")
    }

    ToString()
    {
        return StrGet(NumGet(this.ptr, 8, "UPtr"))  ; LPWSTR PROPVARIANT.pwszVal
    }
}
Updated 20210606.
Just tried this and it worked flawlessly. Thank you!

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 136 guests