Search code examples
audiooutputautohotkeydevice

AutoHotKey v2 Audio Output Device Toggle


I am trying to make a hotkey using AutoHotKey v2 that toggles through the audio output options using nircmd setdefaultsound. The following program is what I have: it does not give errors, and it gives the MsgBox but it always says "Headphones" and it does not actually change the device.

#Requires AutoHotkey v2.0
;Everything until the first return autoruns
device := "Speakers"
return

; Audio Output Device Toggle
#+a::
{
if (device = "Speakers") 
    device := "Headphones"
else if (device = "Headphones") 
    device := "Speakers"
MsgBox Format("Selected device: {}", device)
run "nircmd.exe setdefaultsounddevice %device%"
}

What is causing this not to work?


Solution

  • Your variable device is not in that hotkey's scope. You'd have to explicitly state that you're using a variable from the global scope. Or in this case what you really want is a static variable in the hotkey's scope.(about local and global)

    And also, you're trying to use the legacy AHK syntax for referring to a variable. And even while inside a string. There's absolutely no way that could work. Here's a fixed script, although I can't comment on what you're doing with nircmd. I don't use it, so I won't know if it will work.

    #Requires AutoHotkey v2.0
    ;Everything until the first return autoruns
    ;device := "Speakers"
    return
    
    ; Audio Output Device Toggle
    #+a::
    {
        ;global device ;to refer from global scope
        static device := "Speakers" ;use a static variable
    
        if (device = "Speakers")
            device := "Headphones"
        else if (device = "Headphones")
            device := "Speakers"
    
        MsgBox("Selected device: " device)
        Run("nircmd.exe setdefaultsounddevice " device)
    }