如何从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];
            });
        }

    }];
}


但是在上面的代码中,艺术品数组始终返回空。为什么?解决办法是什么?

最佳答案

希望这会有所帮助。这段代码可与ios 9和xcode 7一起使用。

而不是使用这一行代码。

albumArtWork = [UIImage imageWithData:[item.value copyWithZone:nil]];


由于元数据格式已更改,请尝试此操作。

albumArtWork=[UIImage imageWithData:[item dataValue]];

08-16 04:47