I need help creating an AppleScript that can tell when Spotify switches to a different song. My goal is to show a notification whenever this happens.
First I tried looking at the player position to see if it was zero, thinking that meant a new track started. But this approach failed because users sometimes restart the same song or jump back to the beginning.
Now I’m thinking about making a script that runs continuously and checks the song title every few seconds to see if it changed. I’m worried this might use too much memory though. Here’s what I have so far but it’s not working:
tell application "System Events"
-- verify both notification app and music player are running
set appRunning to ¬
(count of (every process whose name is "NotificationApp")) > 0
(count of (every process whose name is "Spotify")) > 0
end tell
-- create empty string for storing song name
global previous_track
set previous_track to ""
on idle
tell application "Spotify"
if player state is playing then
copy name of current track to track_name_now
-- compare with previously stored track name
if track_name_now is not previous_track then
copy track_name_now to previous_track
set performer to artist of current track
set record_album to album of current track
tell application "NotificationApp"
-- define notification types
set the notificationTypes to ¬
{"MusicTrackChange"}
-- set which notifications are enabled
set the enabledTypes to ¬
{"MusicTrackChange"}
-- register with notification system
register as application ¬
"Spotify" all notifications notificationTypes ¬
default notifications enabledTypes ¬
icon of application "Spotify"
-- display the notification
notify with name ¬
"MusicTrackChange" title ¬
track_name_now description ¬
performer application name "Spotify"
end tell
end if
return 5
end if
end tell
end idle
Any suggestions on how to make this work properly would be great. Thanks!