如何从MP3文件中获取专辑封面或艺术作品。我的mp3文件保存在NSDocument目录中。我的代码是:
NSURL *fileURL=[[NSURL alloc]initFileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@.mp3",[listOfSong objectAtIndex:currentIndex]]]];
AVAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
if (asset != nil) {
NSArray *keys = [NSArray arrayWithObjects:@"commonMetadata", nil];
[asset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
NSArray *artworks = [AVMetadataItem metadataItemsFromArray:asset.commonMetadata
withKey:AVMetadataCommonKeyArtwork
keySpace:AVMetadataKeySpaceCommon];
UIImage *albumArtWork;
for (AVMetadataItem *item in artworks) {
if ([item.keySpace isEqualToString:AVMetadataKeySpaceID3]) {
// *** WE TEST THE IOS VERSION HERE ***
if (TARGET_OS_IPHONE && NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1) {
NSData *newImage = [item.value copyWithZone:nil];
albumArtWork = [UIImage imageWithData:newImage];
}
else {
NSDictionary *dict = [item.value copyWithZone:nil];
if ([dict objectForKey:@"data"]) {
albumArtWork = [UIImage imageWithData:[dict objectForKey:@"data"]];
}
}
}
else if ([item.keySpace isEqualToString:AVMetadataKeySpaceiTunes]) {
// This doesn't appear to get called for images set (ironically) in iTunes
albumArtWork = [UIImage imageWithData:[item.value copyWithZone:nil]];
}
}
if (albumArtWork != nil) {
dispatch_sync(dispatch_get_main_queue(), ^{
imageView.image = albumArtWork;
[artworkImages addObject:albumArtWork];
});
}
}];
}
但是在上面的代码中,艺术品数组总是返回空白。为什么?解决方案是什么?
答案 0 :(得分:1)
希望这会有所帮助。这段代码适用于ios 9和xcode 7。
而不是使用这行代码。
albumArtWork = [UIImage imageWithData:[item.value copyWithZone:nil]];
试试这个,因为元数据格式已经改变了。
albumArtWork=[UIImage imageWithData:[item dataValue]];