Skip to content

Instantly share code, notes, and snippets.

@ieatfood
Forked from jaredmoody/Connect Airpods.applescript
Last active April 17, 2025 05:03
Show Gist options
  • Save ieatfood/814b065964492f71f728da59a47413bc to your computer and use it in GitHub Desktop.
Save ieatfood/814b065964492f71f728da59a47413bc to your computer and use it in GitHub Desktop.
An Applescript to connect bluetooth devices, such as Airpods. Nice when paired with an alfred trigger.
# Taken from https://www.reddit.com/r/MacOS/comments/i4czgu/big_sur_airpods_script/gck3gz3/
# by https://github.com/smithumble
use framework "IOBluetooth"
use scripting additions
set AirPodsName to "AirPods"
on getFirstMatchingDevice(deviceName)
repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)
if (device's nameOrAddress as string) contains deviceName then return device
end repeat
end getFirstMatchingDevice
on toggleDevice(device)
if not (device's isConnected as boolean) then
device's openConnection()
return "Connecting " & (device's nameOrAddress as string)
else
device's closeConnection()
return "Disconnecting " & (device's nameOrAddress as string)
end if
end toggleDevice
return toggleDevice(getFirstMatchingDevice(AirPodsName))
@jorgeacruz
Copy link

Connect + Change the audio output device to Airpords

There is a popular problem when AirPods: when they switch from MacBook to iPhone, sometimes they don't connect back. Even if they get reconnected, the audio output still does not get changed back to AirPods.

I've adjusted @ieatfood implementation:

  1. Always try to connect, never try to disconnect.
  2. Use switchaudio-osx (brew install switchaudio-osx or port install switchaudio-osx) to change the audio output device to AirPods
  3. Add to Automator as a Quick Action (see screenshot below) + Apple manual
  4. Add the Quick Actions button to the Touch Bar

Now I have a TouchBar button that instantly gives my sound back.

use framework "IOBluetooth"
use scripting additions

set AirPodsName to "AirPods Pro (Дмитрий)"

on getFirstMatchingDevice(deviceName)
	repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)
		if (device's nameOrAddress as string) contains deviceName then return device
	end repeat
end getFirstMatchingDevice

on toggleDevice(device)
	set quotedDeviceName to quoted form of (device's nameOrAddress as string)
	
	if not (device's isConnected as boolean) then
		device's openConnection()
	end if
	
	do shell script "/usr/local/bin/SwitchAudioSource -s " & quotedDeviceName
	return "Connecting " & (device's nameOrAddress as string)
end toggleDevice

return toggleDevice(getFirstMatchingDevice(AirPodsName))

image

Woowwww.....it's working! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment