通过ScriptingBridge在iTunes中播放特定标题

时间:2012-02-21 14:50:09

标签: objective-c xcode4 itunes scripting-bridge

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

我想播放一个给定名字的歌曲,但看起来似乎无法做到这一点。我在iTunes.h中找不到类似的东西......

在AppleScript中,它只有三行代码:

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

然后iTunes开始播放经典披头士乐队的歌曲。 有没有我可以使用ScriptingBridge执行此操作,还是必须从我的应用程序运行此AppleScript?

1 个答案:

答案 0 :(得分: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];

方法二

如上所述获取指向iTunes资料库的指针。然后使用脚本桥searchFor: only:方法:

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];

警告方法二:iTunes.h文件错误地声称searchFor: only:方法返回一个iTunesTrack *,实际上(出于显而易见的原因)它返回SBElementArray *。您可以编辑头文件以消除生成的编译器警告。