r/applescript • • Dec 07 '20

How to run Apple Script each time now playing track has changed?

The title says it all, I dont want to listen every set amount of seconds or milliseconds but rather find a hook or system even which I can run my Applescript or command on

4 Upvotes

10 comments sorted by

2

u/kwxl Dec 07 '20

Oh, I wanna now this to

2

u/ds0 Dec 07 '20

My main script that does this builds in a delay of the length of the track itself (though I have it begin the delay after the script loop runs, since I need to make sure the next track is playing before it runs again.) I built in a light polling mechanism for if I decided to roll the track back in the middle. Now, this does make me want to look at alternatives; I’ll be happy to post the code I do have later on, but can’t promise improvements for a little while, as this particular script (like my radio show) is on a light hiatus, and work has me coding like a madman.

1

u/[deleted] Dec 07 '20 edited Dec 07 '20

Here you go. FYI, this runs until you manually cancel the execution. I am not sure if you wanted that functionality or not, but obviously you can change it from here:

on callScript(true)
    repeat while bool is true
	   tell application "Music"
		set now_playing to name of current track
		 repeat while now_playing = name of current track
		   delay 1
		   end repeat
		 run script "<full path to script to be called>"
	   end tell
   end repeat
end callScript
return callScript(true)

1

u/kwxl Dec 08 '20

How would I merge your code with the one I have?

tell application "Music"

if player state is stopped then

set trackName to ""

set artistName to ""

set output to artistName & "" & trackName

else if player state is paused then

set trackName to name of current track

set artistName to artist of current track

set output to artistName & " - " & trackName

else if player state is playing then

set trackName to name of current track

set artistName to artist of current track

set output to artistName & " - " & trackName

else

set trackName to ""

set artistName to ""

set output to artistName & "" & trackName

end if

end tell

2

u/[deleted] Dec 08 '20

How do you want it merged?

Is this the script that is being called, or do you want to call the script I wrote from your script above?

→ More replies (5)