0

How to get album art or artwork from MP3 file. My mp3 file is saved in NSDocument Directory. My code is:

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

    }];
}

But in above code, artworks array always return empty. Why? What is the solution?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Rox
  • 909
  • 11
  • 31

1 Answers1

1

Hope this will help.This piece of code works with ios 9 and xcode 7.

instead of using this line of code.

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

try this,since the metadata format has changed.

albumArtWork=[UIImage imageWithData:[item dataValue]]; 
iOSBoffin
  • 11
  • 3