如何通过ScriptingBridge设置iTunes专辑封面?

时间:2012-10-27 02:31:58

标签: ruby itunes osx-mountain-lion scripting-bridge

今天我发现当我向iTunes添加专辑封面时,它实际上只是将它添加到每张专辑的某些曲目中。所以我做了任何人都会做的事情,并试图编写一个脚本来纠正它。

这是第一次尝试,经过大约3个小时的修补。它假定您已选择了专辑中的所有歌曲。

#! /usr/local/bin/macruby
framework 'Foundation'
framework 'ScriptingBridge'

itunes = SBApplication.applicationWithBundleIdentifier("com.apple.itunes")
tracks = itunes.selection.get

# Find some track with artwork
artwork = tracks.map { |track| track.artworks[0] }.find { |a| a }
raise "No selected song has artwork" if artwork.nil?

# I checked artwork.rawData and it is PNG wrapped in an NSConcreteData.
pngData = artwork.rawData

tracks.each do |track|
  if track.artworks[0]
    puts "[O] #{track.name}"
  else
    puts "[X] #{track.name}"
    # Adding the same artwork object is apparently NG so we get the data from it
    # and make a copy.
    # There is probably a more straight-forward way to clone an object but
    # artwork.copy raises an exception.
    # I have tried using the keys 'data' and 'raw data' instead - same results.
    dict = {rawData: pngData}
    artwork_copy = itunes.classForScriptingClass('artwork').alloc.initWithProperties(dict)

    track.artworks.addObject(artwork_copy)

    raise "Didn't actually add the artwork" if track.artworks.empty?
  end
end

对addObject的调用不会引发异常,但我注意到它并没有实际将艺术作品添加到轨道中(因此检查下一行以加快测试脚本。)

我一直在使用Objective-C的ScriptingBridge示例,并且无法找到其他人也这样做的地方。很多获取艺术作品的例子,但很少有设置它......

我确实从四年前找到了一个有趣的邮件列表帖子,其他人有类似的问题,但他们从来没有找到解决方案(或者发现它并没有将它发布到线程,这更糟糕如果他们这样做,他们就会成为一个坏人并且应该感觉不好。)

1 个答案:

答案 0 :(得分:1)

以下是适用于我的Objective-C代码示例。 我不知道macruby

iTunesApplication *iTunesApp = [SBApplication applicationWithBundleIdentifier: @"com.apple.iTunes"];
SBElementArray *tracks = [[iTunesApp selection] get];
NSArray *trackWithArt = [tracks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"artworks[SIZE] > 0"]]; 
if ([trackWithArt count] > 0) {
    NSImage *tData = (NSImage*)[[[[trackWithArt objectAtIndex:0] artworks] objectAtIndex:0] data];
    for (iTunesTrack *tObj in [tracks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"artworks[SIZE] = 0"]]) {
        [[[[tObj artworks] objectAtIndex:0] propertyWithCode:'pPCT'] setTo:tData];
    }
}

这是另一种有效的方法:

用以下内容替换循环中的行:

iTunesArtwork *tArtw = [[tObj artworks] objectAtIndex:0];
tArtw.data = tData; // set the track's artwork

上述两种情况的MacRuby等价物(我出于显而易见的原因使用后者):

    # 0x70504354 = 'pPCT'
    track.artworks.objectAtIndex(0).propertyWithCode(0x70504354).setTo(artwork.data)
    # or,
    track.artworks.objectAtIndex(0).data = artwork.data

-

另一种选择:使用AppleScript非常简单。