如何在Applescript中等待文件添加到iTunes

如何在Applescript中等待文件添加到iTunes,applescript,itunes,Applescript,Itunes,我有下面的AppleScript向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

我有下面的AppleScript向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
要添加的文件是音频文件,通常长达2小时。当我运行脚本时,我经常在
行上得到错误
error:error in user parameter list(paramErr:-50)
将\u轨迹的名称设置为\u轨迹\u name
。我的猜测是,将文件从临时位置复制到iTunes库时出现了延迟,而且
曲目还不可用

如您所见,我已尝试添加5秒的延迟,但这仍然无法防止问题。通过手动运行脚本,我可以在50%-75%的时间内重新创建问题。出错时iTunes正在运行


我认为我应该在
add
语句之后创建一个循环,以等待导入有效,但我不知道要检查什么。

我看不到任何直接的方法来测试文件是否准备好处理,但在循环中测试错误是很容易的:

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
如果重命名轨迹错误,循环将跳转到错误部分。如果错误为预期的'-50',则循环延迟半秒并重试;如果发生其他错误,脚本将显示错误对话框。如果重命名轨迹成功,脚本将退出循环并继续处理


您可以将其他命令放在try块内或之后,视情况而定。无论哪种方式,我都能看到利弊,这取决于你可能看到的错误类型。

这是一个非常好的建议,它确实起到了作用!我不得不把所有的
集合
放在try块中,因为其他人会偶尔失败。谢谢