Search code examples
applescriptitunes

How to wait for a file to be added to iTunes in Applescript


I have the following AppleScript to add a new file to iTunes

tell application "iTunes"
    launch
    set the_track_ref to add the_filename as POSIX file as alias
    -- delay 5 -- This prevents "Error: error in user parameter list (paramErr:-50)"
    set the_track to contents of the_track_ref
    set the name of the_track to the_track_name -- This sometimes results in "Error: error in user parameter list (paramErr:-50)"
    set the album of the_track to the_track_album
    set the artist of the_track to the_track_artist
    set the genre of the_track to the_track_genre
end tell

The file to add is an audio file, typically 2 hours long. When I run the script, I often get the error Error: error in user parameter list (paramErr:-50) on the line set the name of the_track to the_track_name. My guess is that there is a delay in copying the file from a temporary location to the iTunes library and the_track is not yet available.

As you can see, I have tried adding a delay of 5 seconds, but this still does not prevent the problem. I can recreate the problem 50%-75% of time by running the script manually. iTunes is running at the time of the error.

I think that I should create a loop after the add statement to wait for the import to be valid, but I don't know what to check for.


Solution

  • I don't see any direct way to test whether the file is ready to be processed, but it's easy enough to test for the error in a loop:

    tell application "iTunes"
        launch
        set the_track_ref to add the_filename as POSIX file as alias
        set the_track to contents of the_track_ref
        repeat
            try
                set the name of the_track to the_track_name
                exit repeat
            on error errstr number errnum
                if errnum = -50 then
                    delay 0.5
                else
                    display alert "Error " & errnum & ": " & errstr
                end if
            end try
        end repeat
    end tell
    

    If renaming the track errors out, the loop jumps to the error section. If the error is the expected '-50' the loop delays a half-second and tries again; if some other error occurs, the script displays an error dialog. If renaming the track succeeds, the script exits the loop and continues processing.

    You can put the other commands inside the try block or after it, as you see fit. I can see pros and cons either way, depending on the kinds of errors you're likely to see.