Search code examples
applescriptitunespolling

Itunes Applescript event


I am writing a jukebox application that uses a php/js as a frontend and uses itunes as a backend. The problem is I need a way to tell when a song has stopped playing in itunes. I have thought of using a idle script to poll itunes via applescript. But, I would have to poll every so many seconds, instead I would like a event to run a applescript when the song stops playing. Any ideas?


Solution

  • I'm not entirely sure if a method exists that allows you to do that, but for now you could always use iTunes' player state property, which tells you what iTunes is currently doing by returning one of the following five values:

    playing, stopped, paused, fast forwarding, rewinding
    

    Using that property, you can then create a repeat until player state is stopped loop with no commands inside of it (in essence, wait until the song currently playing is stopped), then after the loop, execute whatever you want. Translated into code, this paragraph reads:

    tell application "iTunes"
       repeat until player state is stopped
          --do nothing until the song currently playing is stopped...
       end repeat
       --[1]...and then execute whatever you want here
    end tell
    

    OPTIONAL

    If you only want to run the script once, you could insert the above script into an infinite repeat loop, although you might want to delay a bit first to allow you to start a song. Otherwise, [1] will execute immediately after you start the script (assuming no songs are in use).

    Code

    repeat
      delay 60 --1 minute delay
      tell application "iTunes"
         repeat until player state is stopped
             --wait
         end repeat
         ...
      end tell
    end repeat
    

    If you have any questions, just ask. :)