2012-02-21 104 views
1

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

我想用给定的名字播放歌曲,但看起来没有办法做到这一点。我没有找到iTunes.h任何类似的事情......

在AppleScript的,它只是三行代码:

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

然后iTunes中开始播放的经典甲壳虫乐队的歌曲。 有没有我能用ScriptingBridge做到这一点,还是我必须从我的应用程序运行这个AppleScript?

回答

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 *。您可以编辑头文件以摆脱由此产生的编译器警告。

+0

是的,它并不像AppleScript版本那么简单,但它非常棒!谢谢! – Chris 2012-02-23 18:51:38

+0

请注意,对于那些下面的方法二(至少我的iTunes.h)库应该是libraryPlayList,并且kSrS应该用单引号,或者甚至更好地使用itunes.h定义的枚举:iTunesESrASongs – mackworth 2013-05-26 18:24:33

相关问题