0

I am building a music player app and my .mp3 files come from the /Documents directiory in iOS 11. Thing is that I found out after a research how to read those files from the folder.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

NSError *error;
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];

NSLog(@"%@", directoryContents);

The above code gets the the file name which I will print out later in a UITableViewController.

My issue is that now I dont know how to read the .mp3's metadata from the /Documents folder such as artist, or album artwork.

1 Answers1

0

If you have a path to a .mp3 file, try doing this:

 - (void)getMetaDataForSong:(NSString *)pathToMP3File {

   // pathToMP3File should looks something like this: 
   // /var/mobile/Applications/741647B1-1341-4203-8CFA-9D0C555D670A/Library/Caches/All Summer Long.m4a
    NSURL *mp3FileURL = [NSURL fileURLWithPath: pathToMP3File];
    NSLog(@"%@", [mp3FileURL absoluteString]);
    asset = [[AVURLAsset alloc] initWithURL: mp3FileURL options:nil];
    NSLog(@"%@", asset);

    for (NSString *format in [asset availableMetadataFormats]) {
      for (AVMetadataItem *item in [asset metadataForFormat:format]) {
        if ([[item commonKey] isEqualToString:@"title"]) {
            musicItem.strSongTitle = (NSString *)[item value];
        } 
        if ([[item commonKey] isEqualToString:@"artist"]) {
            musicItem.strArtistName = (NSString *)[item value];
        }
        if ([[item commonKey] isEqualToString:@"albumName"]) {
          musicItem.strAlbumName = (NSString *)[item value];
        }
        if ([[item commonKey] isEqualToString:@"artwork"]) {
          UIImage *img = nil;
          if ([item.keySpace isEqualToString:AVMetadataKeySpaceiTunes]) {
            img = [UIImage imageWithData:[item.value copyWithZone:nil]];
          }
          else { // if ([item.keySpace isEqualToString:AVMetadataKeySpaceID3]) {
            NSData *data = [(NSDictionary *)[item value] objectForKey:@"data"];
            img = [UIImage imageWithData:data]  ;
          }
          musicItem.imgArtwork = img;
        }
     }
  }
}

This code comes straight from this related question.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Thank you for you help :) . It works fine mostly. Only thing is that a they stated in the related question you pointed, code crashed on `NSData *data = [(NSDictionary *)[item value] objectForKey:@"data"];img = [UIImage imageWithData:data] ;` And i don't have enough reputation to ask with a comment. Do you maybe know whats wrong with that piece of code. Thanks again –  Mar 11 '18 at 15:41