[AppleScript] 利用Alfred快速鍵快速連線/斷線你的Airpods或其他藍牙裝置

故事是這樣的:

最近因為每天上班會用Airpods連公司PC,下班回家連我自己的macbook air

因為藍牙預設連線會自動去連上一個連接過的裝置,所以如果要在不同裝置間換來換去,勢必是要手動切換,所以就因為懶人如我,才會想要將這個無聊的過程自動化(會去研究這個才無聊吧XD)

這段程式是能點擊mac menubar上的藍牙icon,並判斷如果是有出現”連線”或”連線中斷”,因為這兩個只會出現一種,不會有其他情況,所以我這邊改的邏輯就用很簡單,有需要的人可以自己去更改符合自己需求的版本~


編寫AppleScript

先打開『工序指令編寫程式.app』(英文是Script Editor.app),可以用spotlight(⌘+空白鍵),打『工序指令編寫程式.app』或『Script Editor.app』,也可以打開你的Launchpad,找到像下圖這樣的app

再把下面這段程式碼貼上

activate application "SystemUIServer"
tell application "System Events"
	tell process "SystemUIServer"
		-- Working CONNECT Script.  Goes through the following:
		-- Clicks on Bluetooth Menu (OSX Top Menu Bar)
		--    => Clicks on RS airpods Item
		--      => Clicks on Connect Item
		set btMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth")
		tell btMenu
			click
			tell (menu item "RS airpods" of menu 1)
				click
				if exists menu item "連線" of menu 1 then
					click menu item "連線" of menu 1
					return "Connecting..."
				else if exists menu item "中斷連線" of menu 1 then
					click menu item "中斷連線" of menu 1
					return "Disconnecting..."
				else
					click btMenu
					return "Connect menu was not found, are you already connected?"
				end if
			end tell
		end tell
	end tell
end tell

出處原code大神:AppleScript to Connect BlueTooth Headphones


拿這段程式碼的人要改的地方就是

1. 

tell (menu item "RS airpods" of menu 1)

雙引號裡的RS airpods,改成你自己為你的airpods所取的名字

ps. 這個裝置名稱可以改為你的任何藍牙裝置名稱,但是相對應的程式邏輯就不一定會像我寫得這樣

2. 如果你的系統語言是英文或其他語言,就把有出現”連線”、”中斷連線”替換成你們語言的字,根據你的menubar所顯示的字面去改


測試AppleScript是否能用

點擊下方圈起的播放鍵

確定可以後,再往下一步,給他一個全域的快速鍵~


建立Alfred的workflow

我設定快速鍵為⌘+ctrl+shift+A,會自動執行我們剛剛寫的AppleScript,就可以隨時連上airpods、隨時讓他斷線囉,雖然不會有什麼情況是要讓他斷線的XD

作者

RongSon

Graduate Student of CCU COMM Game Development, Network Communication, macOS/Ubuntu/Android, Arduino/Raspberry Pi/Intel Edison, Java/Python/C/C++

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *