1

我正在尝试编写一个通过 ScriptingBridge 与 iTunes 交互的应用程序。到目前为止我工作得很好,但这种方法的选择似乎非常有限。

我想播放给定名称的歌曲,但看起来没有办法做到这一点。我在 iTunes.h 中没有找到类似的东西……</p>

在 AppleScript 中只有三行代码:

tell application "iTunes"
    play (some file track whose name is "Yesterday")
end tell

然后 iTunes 开始播放经典的披头士歌曲。有没有我可以用 ScriptingBridge 做到这一点,还是我必须从我的应用程序运行这个 AppleScript?

4

1 回答 1

4

它不像 AppleScript 版本那么简单,但它肯定是可能的。

方法一

获取指向 iTunes 资料库的指针:

iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
SBElementArray *iTunesSources = [iTunesApp sources];
iTunesSource *library;
for (iTunesSource *thisSource in iTunesSources) {
    if ([thisSource kind] == iTunesESrcLibrary) {
        library = thisSource;
        break;
    }
}

获取包含库中所有音频文件轨道的数组:

SBElementArray *libraryPlaylists = [library libraryPlaylists];
iTunesLibraryPlaylist *libraryPlaylist = [libraryPlaylists objectAtIndex:0];
SBElementArray *musicTracks = [self.libraryPlaylist fileTracks];    

然后过滤数组以查找具有您要查找的标题的曲目。

NSArray *tracksWithOurTitle = [musicTracks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"%K == %@", @"name", @"Yesterday"]];   
// Remember, there might be several tracks with that title; you need to figure out how to find the one you want. 
iTunesTrack *rightTrack = [tracksWithOurTitle objectAtIndex:0];
[rightTrack playOnce:YES];

方法二

Get a pointer to the iTunes library as above. Then use the Scripting Bridge searchFor: only: method:

SBElementArray *tracksWithOurTitle = [library searchFor:@"Yesterday" only:kSrS];
// This returns every song whose title *contains* "Yesterday" ...
// You'll need a better way to than this to pick the one you want.
iTunesTrack *rightTrack = [tracksWithOurTitle objectAtIndex:0];
[rightTrack playOnce:YES];

Caveat to method two: The iTunes.h file incorrectly claims that the searchFor: only: method returns an iTunesTrack*, when in fact (for obvious reasons) it returns an SBElementArray*. You can edit the header file to get rid of the resulting compiler warning.

于 2012-02-22T01:55:39.843 回答