Q: How to set the current audio device to airplay speaker in Apple Script? How do I programmatically switch the current output device between built-in speakers on my MacBook Pro and a HomePod Mini (via Airplay) in AppleScript?

A: This can be done using the Switch Audio Source CLI program and the following script:

*

*Install switchaudio-osx via Homebrew.

brew install switchaudio-osx



*Use the following script (for example, as a workflow in Automator).

property airPlayDevice : "Bedroom"
property localDevice : "MacBook Pro Speakers"

set the currentAudioSource to (do shell script "/usr/local/Cellar/switchaudio-osx/1.1.0/SwitchAudioSource -c")
set the availableAudioSources to paragraphs of (do shell script "/usr/local/Cellar/switchaudio-osx/1.1.0/SwitchAudioSource -a")

if currentAudioSource is equal to localDevice then
    if availableAudioSources contains "Airplay" then
        -- Airplay device is already connected but not set as current output device.
        switchToDevice("Airplay")
    else
        -- Connect to an Airplay device 
        connectToAirPlayDevice()
    end if
else
    switchToDevice(localDevice)
end if

-- Switch the current device using switchaudio-osx.
on switchToDevice(device)
    do shell script "/usr/local/Cellar/switchaudio-osx/1.1.0/SwitchAudioSource -s " & quoted form of device
end switchToDevice

-- Connect to the first available AirPlay device
on connectToAirPlayDevice()
    tell application "Audio MIDI Setup" to activate
    tell application "System Events"
        click menu button 1 of splitter group 1 of window "Audio Devices" of application process "Audio MIDI Setup"
        click menu item "Connect AirPlay Device" of menu 1 of menu button 1 of splitter group 1 of window "Audio Devices" of application process "Audio MIDI Setup"
        set the availableDevice to "No AirPlay devices available"
        repeat while availableDevice is "No AirPlay devices available"
            set availableDevice to name of first menu item of menu 1 of menu item "Connect AirPlay Device" of menu 1 of menu button 1 of splitter group 1 of window "Audio Devices" of application process "Audio MIDI Setup"
        end repeat
        click (menu item airPlayDevice of menu 1 of menu item "Connect AirPlay Device" of menu 1 of menu button 1 of splitter group 1 of window "Audio Devices" of application process "Audio MIDI Setup")
    end tell
    tell application "Audio MIDI Setup" to quit
end connectToAirPlayDevice

