I have an Applescript that connects a bluetooth speaker to my Mac and switches “Play sound effects through:” to “Internal Speakers”.
I want this script to run every time I turn on my bluetooth speaker. I am currently triggering the script manually with a keyboard shortcut every time I switch the speaker on, but it would be even more convenient if I could set the script to run automatically whenever the bluetooth speaker becomes available to the Mac, preferably without using third-party software.
Is there a way to do this?
Best Answer
This is a sort of tricky thing to do if you don't want to use 3rd party software. However, with some bash and plist scripting we can get it to work!
First, in your
~/Library/LaunchAgents
folder create the following .plist file (in this case I have named itcom.my.bluetoothdetector.plist
; if you change the name, make sure to change line 4 in the file as well):The above file will call whatever script is located at
/Users/YOURUSERNAME/Desktop/script.sh
when there is a change in the Bluetooth environment. You can of course change the location of the file called from the Desktop to wherever you want (ensuring that it is a full path).Now, we will make a bash script, which, when triggered by our
com.my.bluetoothdetector.plist
file, will check whether your device is connected. In this case, we will save this file to/Users/USERNAME/Desktop/script.sh
:Here, substitute
BLUETOOTHDEVICENAME
for the name of your device and the/Applications/YOURAPPNAME.app
part of theopen /Applications/YOURAPPNAME.app
command for the location of the Automator/AppleScript app you want to run. You could also replace this line entirely to run any shell script you want when the device is connected which may negate the need for you to have a separate AppleScript/Automator app to be called.Finally, use the command:
This will start up the process which will check for the change in the Bluetooth environment and then call the
script.bash
when this is detected.Now, hopefully, when you connect the Bluetooth device to your computer, after just a few seconds, your AppleScript/Automator file should run!
Previously connected bluetooth devices should connect automatically to a Mac when they become available. If this isn't the case for you, maybe there is some sort of problem to do with your bluetooth settings. Have a look at this article if the problem persists.
P.S. In the future, if you want to delete this, run the following commands: