Synny Synny - 6 months ago 52
iOS Question

Get info of audio file with his path - Objective-c iOS

Actually, I'm playing a song with this simple part of code:

NSURL *url=[NSURL fileURLWithPath:clickedPath];
AVPlayer *player = [AVPlayer playerWithURL:url];


AVPlayerViewController *controller = [[AVPlayerViewController alloc] init];
[self presentViewController:controller animated:YES completion:nil];
controller.player = player;
[player play];


What I would like to do is showing the song's info (artist, album name and artwork, etc...) using a custom view showed with contentOverlayView's property of AVPlayerViewController.
I've searched all around here but found nothing that would be useful for my case (either found MPMediaPlayer solution or not working ones).

Coule you help me please ? I'm open to test your suggestions and discuss about it !

Thanks in advance

L A L A
Answer
NSString *path = [[NSBundle mainBundle] pathForResource:@"youraudiomp3filename" ofType:@"mp3"];

NSURL *url=[NSURL fileURLWithPath:path];
AVPlayer *player = [AVPlayer playerWithURL:url];

AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];

NSArray *metadata = [asset commonMetadata];
NSString *title;
NSString *artist;
NSString *albumName;
UIImageView *imageView;
for (AVMetadataItem *item in metadata) {
    if ([[item commonKey] isEqualToString:@"title"]) {
        title = (NSString *)[item value];
    }

    if ([[item commonKey] isEqualToString:@"artist"]) {
        artist = (NSString *)[item value];
    }

    if ([[item commonKey] isEqualToString:@"albumName"]) {
        albumName = (NSString *)[item value];
    }

    if ([[item commonKey] isEqualToString:@"artwork"]) {
        NSData *data = [(NSDictionary *)[item value] objectForKey:@"data"];
        UIImage *img = [UIImage imageWithData:data] ;
        imageView.image = img;
        continue;
    }
}

then you can set the asset to the player of your AVPlayerViewController, play and present.

Comments