2012-02-21 40 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

相關問題