Connecting AirPlay displays with a keystroke

airplayapplescriptautomationautomatorterminal

I have an Apple TV in the living room. I have a Mac mini in my office. I have a wireless keyboard and mouse that can easily reach between the two locations, but am not willing to walk between them to turn on Airplay.

I'd like to connect via AirPlay with a keystroke from my wireless keyboard, which would turn on Airplay to my living room computer. I would prefer this to be silently performed in the background.

This is apparently quite difficult. I spent two hours on the command line approach. I found no working commands. This is very surprising to me.

I've attempted connecting using Automator with a Run AppleScript action selecting the menu item as a service with a keystroke.

The AppleScript code:

on run {input, parameters}
    
    tell application "System Events"
        tell process "SystemUIServer"
            click (menu bar item 1 of menu bar 1 whose description contains "Displays Menu")
            key code 125
            key code 125
            keystroke return
            delay 5
        end tell
    end tell
    return input
end run

It works from Automator. It only runs when Finder is frontmost, and even then it requires me first to open the Finder > Services menu once (not even choose anything, just open that). This seems to be a known bug…

I need this command to work all the time, without any mouse input (because I cannot see my screen).

Any suggestions as to a viable path forward would be very much appreciated.

Best Answer

If you first brought finder to the front in the script, would it work:

   on run {input, parameters}
    tell application "Finder" to activate
    tell application "System Events"
        tell process "SystemUIServer"
            click (menu bar item 1 of menu bar 1 whose description contains "Displays Menu")
            key code 125
            key code 125
            keystroke return
            delay 5
        end tell
    end tell
    return input
end run