Jump to content

AppleScript: Hiding audio menu bar dropdown if not clicking item


Recommended Posts

Hey

 

I'm trying to make an AppleScript to be run from Alfred, that should quickly set a specified speaker as audio output device if it is currently connected (in example below "My Awesome Speaker"), and otherwise don't do anything. I have gotten most of the functionality down (toggling between speaker/internal speaker), but I'm having a problem in the instance that the speaker isn't connected.

 

When this is the case, the script has already clicked on the audioMenu, making the dropdown be there until a mouse click. I thought I could make it go away by branching with an "if else" and then if the speaker isn't connected, then just clicking the audioMenu again (because I've seen similar behaviour (with succes) for other menu bar scripts). But if I instead do this, the audio dropdown will still be staying until a click has been made, and then the script clicks the audio icon again making it doubly annoying.

 

 

on alfred_script(q)

set speakerName to "My Awesome Speaker"
set internalSpeakers to "Internal Speakers"

activate application "SystemUIServer"
tell application "System Events"
	tell process "SystemUIServer"
		-- Working CONNECT Script.  Goes through the following:
		-- Clicks on Audio Menu (OSX Top Menu Bar)
		-- Clicks your speaker if not connected
		-- Else if connected, then disconnects by clicking Internal Speakers
		set audioMenu to menu bar item 4 of menu bar 1
		tell audioMenu
			click
			if exists menu item speakerName of menu 1 then
				set speakerMenuItem to menu item speakerName of menu 1
				if value of attribute "AXMenuItemMarkChar" of speakerMenuItem is "✓" then
					click menu item internalSpeakers of menu 1
					return "Disconnecting from " & speakerName & "..."
				else
					click speakerMenuItem
					return "Connecting to " & speakerName & "..."
				end if
			else
				-- Doesn't work for now. Just clicks it again after you deselect menu, making it double annoying
				--click audioMenu
				return "Doesn't look like you're connected to " & speakerName & "..."
			end if
		end tell
	end tell
end tell
end alfred_script

How can I fix this, so the dropdown actually goes away if speaker is not connected?

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...