Gerry Tonkin-Hill

Shut up Spotify!

Myspace (xkcd)

Apart from when I’m forced to work from home I have generally worked in open plan offices. One of my big fears each day is that I will open my laptop and whatever embarrassing song I was listening to will immediately start playing on full volume for everyone to hear.

Recently I bought a new pair of bluetooth headphones that conveniently allow you to connect to multiple devices at once. Annoyingly, they will force Spotify to pause if you have the Spotify app open on both devices, even when your laptop lid is closed.

This finally motivated me to look into how I could force Spotify to quit whenever I closed my laptop.

After some searching on StackOverflow I found that you can run a script to check whether a mac laptop’s lid is open or closed. Some further Googling introduced me to LaunchDaemons which allow you to automatically run a process in the background whenever the computer starts up. Using this, I could frequently query the status of the lid and issue a command to quit Spotify and set the system volume to mute if the lid was closed.

The script is relatively straight forward

 1while sleep 5 #check every 5 seconds
 2    do 
 3    number=$(ps aux | grep -v grep | grep -ci Spotify) #check whether spotify is open
 4    lid=$(ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState  | grep -ci 'No') #check whether the lid is open
 5    if [ $lid -eq 0 ] && [ $number -gt 0 ]
 6        then 
 7        /usr/bin/osascript -e 'quit app "Spotify"' # quit spotify
 8        /usr/bin/sosascript -e "set Volume 0" # mute the system volume
 9    fi
10 done

This can then be packaged up into a .plist file and placed into /Users/username/Library/LaunchAgents folder so that it runs in the background everytime you start up your laptop. The resulting .plist file looks like

 1<?xml version="1.0" encoding="UTF-8"?>
 2<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
 3 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
 4<plist version="1.0">
 5<dict>
 6    <key>Label</key>
 7    <string>shutup-spotify</string>
 8    <key>Program</key>
 9    <string>/usr/bin/osascript</string>
10    <key>Program</key>
11    <string>/bin/sh</string>
12    <key>ProgramArguments</key>
13    <array>
14        <string>sh</string>
15        <string>-c</string>
16        <string>while sleep 5; do number=$(ps aux | grep -v grep | grep -ci Spotify); lid=$(ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState  | grep -ci 'No'); if [ $lid -eq 0 ] && [ $number -gt 0 ]; then /usr/bin/osascript -e 'quit app "Spotify"'; /usr/bin/sosascript -e "set Volume 0"; fi; done</string>
17    </array>
18    <key>ServiceDescription</key>
19    <string>Auto Keypress</string>
20    <key>KeepAlive</key>
21    <true/>
22</dict>
23</plist>

I am very new at writing .plist files so I’m sure there are improvements that could be made. But for now, I can finally relax when opening my laptop!