iOS AVFoundation: How do I fetch artwork from an mp3 file?

前端 未结 3 1210
粉色の甜心
粉色の甜心 2020-11-29 06:41

My code:

- (void)metadata {
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:self.fileURL options:nil];

NSArray *artworks = [AVMetadataItem metadataItemsFrom         


        
3条回答
  •  悲&欢浪女
    2020-11-29 07:23

    I just found the answer to that here: How can I extract metadata from mp3 file in ios development and was now looking to see why that code doesn't work on an m4a file. I took a little bit from your code and present the following which seems to work for both m4a and mp3. Note that I left the code which works for mp3 as an open else clause without the qualifier - if anybody gains more experience with this they are welcome to refine!

     - (void)getMetaDataForSong:(MusicItem *)musicItem {
       AVAsset *assest;
    
       // filePath looks something like this: /var/mobile/Applications/741647B1-1341-4203-8CFA-9D0C555D670A/Library/Caches/All Summer Long.m4a
    
        NSURL *fileURL = [NSURL fileURLWithPath:musicItem.filePath];
        NSLog(@"%@", fileURL);
        assest = [AVURLAsset URLAssetWithURL:fileURL    options:nil];
        NSLog(@"%@", assest);
    
        for (NSString *format in [assest availableMetadataFormats]) {
          for (AVMetadataItem *item in [assest 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;
            }
         }
      }
    }
    

提交回复
热议问题