如何在/ Documents文件夹中获取文件元数据?

时间:2018-03-10 21:46:06

标签: ios objective-c

我正在构建一个音乐播放器应用程序,我的.mp3文件来自iOS 11中的/ Documents directiory。事情是我在研究后发现如何从文件夹中读取这些文件。

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

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

NSLog(@"%@", directoryContents);

以上代码获取的文件名将在稍后的UITableViewController中打印出来。

我的问题是,现在我不知道如何从/ Documents文件夹中读取.mp3的元数据,例如艺术家或专辑图片。

1 个答案:

答案 0 :(得分:0)

如果您有.mp3文件的路径,请尝试执行以下操作:

 - (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;
        }
     }
  }
}

此代码来自straight from this related question