iOS: Getting and displaying album artwork from iPod library
Asked Answered
A

2

5

I want to get the album art from a audiobook in the iPod library, But I do not understand how to use MPMediaItemPropertyArtwork

- (NSArray *)audiobooks
{
    MPMediaPropertyPredicate *abPredicate =
    [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:MPMediaTypeAudioBook]
                                     forProperty:MPMediaItemPropertyMediaType];

    MPMediaQuery *abQuery = [[MPMediaQuery alloc] init];
    [abQuery addFilterPredicate:abPredicate];
    [abQuery setGroupingType:MPMediaGroupingAlbum];
    NSArray *books = [abQuery collections];
    return books;
}

- (MPMediaItem *)mediaItemForRow: (NSInteger)row
{
    NSArray *audiobooks = self.audiobooks;
    MPMediaItem *mediaItem = nil;

    for (id object in audiobooks) {
        if ([object isKindOfClass:[MPMediaItemCollection class]]) {
            MPMediaItemCollection *book = (MPMediaItemCollection *)object;

            id item = [book items][row];
            if ([item isKindOfClass:[MPMediaItem class]]) {
                mediaItem = (MPMediaItem *)item;

            }
        }
    }
    return mediaItem;
}

So now I can get title of media item like this:

NSString *title = [mediaItem valueForProperty:MPMediaItemPropertyArtist];

But how do i get the artwork so I can display it in a UIImage? there is this property:

[mediaItem valueForProperty:MPMediaItemPropertyArtwork]

I have not managed to find out how to use it.

Aught answered 25/8, 2013 at 8:49 Comment(2)
possible duplicate of Not able to get the UIImage from MPMediaItemPropertyArtWorkLemus
Here is a useful reference: #28979513Paradisiacal
L
9

You should be able to fetch the artwork into a UIImage via the following:

MPMediaItemArtwork *itemArtwork = [mediaItem valueForProperty:MPMediaItemPropertyArtwork];
UIImage *artworkUIImage = [itemArtwork imageWithSize:CGSizeMake(64, 64)];

In essence, the MPMediaItemPropertyArtwork property returns a MPMediaItemArtwork which you can then obtain a UIImage from.

Lemus answered 25/8, 2013 at 8:55 Comment(2)
Thanks! just as a note the imageWithSize method seems to not resize the image, but instead return fixed size of either 64x64 or 48x48, maybe something to do with my tableView cell, but I don´t think so.Aught
@TomLilletveit As you imply, I suspect it's the UITableViewCell that's determining the displayed size of the UIImage.Lemus
I
1

I have just converted the above answer to Swift 3:

let songInfo: MPMediaItem = self.arrSongs[indexPath.row] as! MPMediaItem

// Song Info is Media Item.

 let itemArtwork :MPMediaItemArtwork  = songInfo.artwork!
 cell.songImg.image = itemArtwork.image(at: CGSize(width: 50, height: 50))
Ibidem answered 30/6, 2017 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.