How can I extract metadata from mp3 file in ios development

Faisal picture Faisal · Oct 14, 2012 · Viewed 7.4k times · Source

I am working on an ios music player with cloud storage.

I need to extract the music information such as title, artist, artwork.

I have an action called playit which plays and pauses the mp3 file. It should also populate some UILables and UIImage with the metadtaa that is associated with the mp3 file. The problem is that I could not get the metadata extracted from more than different 25 mp3 files. Here is my code:

The file url is correct because the audio player is able to find and play it, but I do not know why avmetadataitem is not able to get the metadata.

- (IBAction)playIt:(id)sender {
AVAudioPlayer *audioPlayer;
AVAsset *assest;

NSString * applicationPath = [[NSBundle mainBundle] resourcePath]; 
NSString *secondParentPath = [applicationPath stringByDeletingLastPathComponent];
NSString *soundFilePath = [[secondParentPath stringByAppendingPathComponent:@"fisal1407"] stringByAppendingPathComponent:[musicFiles objectForKey:@"show_id"] ];

NSURL *fileURL = [NSURL URLWithString:[soundFilePath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

assest = [AVURLAsset URLAssetWithURL:fileURL options:nil];
NSArray *metadata = [assest commonMetadata];
for (NSString *format in metadata) {
    for (AVMetadataItem *item in [assest metadataForFormat:format]) {
        if ([[item commonKey] isEqualToString:@"title"]) {
            filename.text = (NSString *)[item value];
            NSLog(@" title : %@", (NSString *)[item value]);
        } 
        if ([[item commonKey] isEqualToString:@"artist"]) {
            show_id.text = (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;
         }
    }
 }

   if (audioPlayer == nil) {

    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
    audioPlayer.numberOfLoops = -1;

   [audioPlayer play];
    [sender setImage:[UIImage imageNamed:@"player_044.gif"] forState:UIControlStateNormal];
   }
else
   {
    if (audioPlayer.isPlaying)
    {
        [sender setImage:[UIImage imageNamed:@"player_04.gif"] forState:UIControlStateNormal];
        [audioPlayer pause];
    } else {
        [sender setImage:[UIImage imageNamed:@"player_044.gif"] forState:UIControlStateNormal];
        [audioPlayer play];
    }
 }  
}

Answer

Alex picture Alex · Nov 15, 2012

Try

for (NSString *format in [asset availableMetadataFormats])

Instead of

NSArray *metadata = [assest commonMetadata];
for (NSString *format in metadata) {