转换iTunes applescript以使用更新的iTunes库框架

时间:2017-05-02 12:22:15

标签: applescript itunes

可以将此AppleScript转换为使用iTunes Library framework而不是使用标准的iTunes applescript。

我当前的脚本读取用户iTunes资料库并创建一个由TrackName,TrackLocation和PersistentId组成的文件,它可以正常工作,但当用户拥有大型iTunes资料库时可能会很慢

tell application "iTunes"
    with timeout of 2400 seconds
        if (count of every file track of library playlist 1) is equal to 0 then
            set thePath to (POSIX file "/tmp/songkong_itunes_model.new")
            set fileref to open for access (thePath) with write permission
            set eof fileref to 0
            close access fileref
            return
        end if

        tell every file track of library playlist 1
            script performancekludge
                property tracknames : its name
                property locs : its location
                property persistids : its persistent ID
            end script
        end tell
    end timeout
end tell

set thePath to (POSIX file "/tmp/songkong_itunes_model.new")
set fileref to open for access (thePath) with write permission
set eof fileref to 0

tell performancekludge
    repeat with i from 1 to length of its tracknames
        try
            set nextline to item i of its tracknames ¬
                & "::" & POSIX path of item i of its locs ¬
                & "::" & item i of its persistids
            write nextline & linefeed as «class utf8» to fileref
        end try
    end repeat
end tell
close access fileref

最大的不同是这个新框架并不要求iTunes实际运行,我希望它应该快得多。然而,稀疏指令只讨论ObjectiveC我不清楚我将如何在applescript中编写一个版本(甚至在Java中更好)

1 个答案:

答案 0 :(得分:0)

这是使用iTunesLibrary框架的AppleScriptObjc等效项。它不会逐行写入文本但会创建一个数组,插入新行字符然后立即写入整个文件。在编写文件时,它还使用了更好的错误处理。

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

use framework "iTunesLibrary"

set {library, theError} to current application's ITLibrary's libraryWithAPIVersion:"1.0" |error|:(reference)
if theError is not missing value then
    display dialog theError's localizedDescription() as text buttons {"Cancel"} default button 1
end if
set tracks to library's allMediaItems()

set thePath to "/tmp/songkong_itunes_model.new"

set theLines to {}
repeat with aTrack in tracks
    try
        set nextline to (aTrack's title as text) ¬
            & "::" & (aTrack's location's |path| as text) ¬
            & "::" & (aTrack's persistentID()'s intValue())
        set end of theLines to nextline

    end try
end repeat
set {TID, text item delimiters} to {text item delimiters, return}
set theText to theLines as text
set text item delimiters to TID
try
    set fileref to open for access thePath with write permission
    set eof fileref to 0
    write theText as «class utf8» to fileref
    close access fileref
on error
    try
        close access thePath
    end try
end try