Stop iTunes after current song

ben
Fri, 15 May 2009 23:18:45 +0000

Something I always missed from Foobar2000 is the option to "Stop playback after current song"

For some reason it never occurred to me it would be trivial to write an AppleScript to mimic this for iTunes..

tell application "System Events"
    set cur_app to name of the first process whose frontmost is true
    set visible of process cur_app to false
end tell

tell application "iTunes"
    set last_track_id to id of current track
    set last_track_name to name of current track

    repeat while true
        set cur_track_id to id of current track
        if not last_track_id = cur_track_id then
            stop playing
            exit repeat
        end if
        delay 0.5
    end repeat
end tell

Paste that into the "Script Editor" application (in /Applications/Applescript/). File > Save As. Change filetype to Application, uncheck "Startup Screen" and put it in your Applications folder. Launch it via Quicksilver. Done.

Read-on to see how the script got to this point (not terribly interesting, but might-possibly be informative)...

After a quick search of the iTunes AppleScript docs (in the Script Editor application, Window > Library, double click iTunes), I found the "id of current track" function.

tell application "iTunes"
    set current_track_id to id of current_track
    display dialog current_track_id
end tell

Running that displays a dialogue showing the tracks ID (a number), if you change song and re-run it, you get a different number..

Now you just need to use AppleScript's weird syntax to loop until the current ID changes, then call the "stop playing" command and exit the loop:

tell application "iTunes"
    set last_track_id to id of current track

    repeat while true
        set cur_track_id to id of current track
        if not last_track_id = cur_track_id then
            stop playing
            exit repeat
        end if
        delay 0.5
    end repeat
end tell

I saved that as "stopaftercurrent", put it in ~/Library/Scripts/ and launched it via Quicksilver..

The problem is Quicksilver is tied up until the script exits..

Putting the script in ~/Library/iTunes/Scripts/ and launching via iTunes' script menu has the same issue (but ties up iTunes instead of Quicksilver..)

The simplest way around this is to save the script as an Application.. When you save the script, change "File Format" from "Script" to "Application".

You can launch this via Quicksilver, and it appears as another Dock icon, which quits when the song finishes.

The problem with this is the stopaftercurrent Application becomes the active app, which is annoying.. I want the application to hide itself when launched - so, a more a bit more absurd AppleScript..

tell application "System Events"
    set cur_app to name of the first process whose frontmost is true
    set visible of process cur_app to false
end tell