Toggling between speakers and headphones with Hammerspoon

I tend to switch between using headphones and speakers often, so I made myself a function to toggle the system audio output device with Hammerspoon:

function toggleSpeakersAndHeadphones()
    local speakerName = "MacBook Pro Speakers"
    local headphonesName = "USB-C to 3.5mm Headphone Jack Adapter"
    local currentDevice = hs.audiodevice.defaultOutputDevice()
    local currentName = currentDevice:name()
    local isSpeakers = currentName == speakerName

    if (isSpeakers) then
        local headphones = hs.audiodevice.findDeviceByName(headphonesName)
        headphones:setDefaultOutputDevice()
    else
        local speakers = hs.audiodevice.findDeviceByName(speakerName)
        speakers:setDefaultOutputDevice()
    end
end

If you have multiple devices with the same name or want to set Bluetooth device as output, use hs.audiodevice.findDeviceByUID to get the device instead of findDeviceByName. To get the device ID, use hs.audiodevice.allOutputDevices() or hs.audiodevice.current(), which you can then store as a variable.

function setAudioOutputById(deviceId)
    local device = hs.audiodevice.findDeviceByUID(deviceId)

    if (device) then
        device:setDefaultOutputDevice()
    end
end

Also refer to the hs.audiodevice docs.

You can bind the function to a hotkey or use hs.chooser to have GUI selector for functions. I have mine in my custom chooser with most commonly used applications & scripts.