How to extract metadata from audio files in iOS

I am trying to extract metadata from mp3 and m4a files using the AVFoundation structure.

This is the test code:

+ (void)printMetadataForFileAtPath:(NSString *)path { NSURL *url = [NSURL fileURLWithPath:path]; AVAsset *asset = [AVURLAsset assetWithURL:url]; NSArray *availableFormats = [asset availableMetadataFormats]; NSLog(@"Available formats: %@", availableFormats); NSArray *iTunesMetadata = [asset metadataForFormat:AVMetadataFormatiTunesMetadata]; for (AVMetadataItem *item in iTunesMetadata) { NSLog(@"%@ %x", item.key, [(NSNumber *)item.key integerValue]); if ([item.key isEqual:AVMetadataiTunesMetadataKeySongName]) { NSLog(@"FOUND song name: %@", item.stringValue); } } NSLog(@"===================="); NSLog(@"%@ %@ %@", AVMetadataiTunesMetadataKeySongName, AVMetadataiTunesMetadataKeyAlbum, AVMetadataiTunesMetadataKeyArtist); } 

This is the conclusion:

 Available formats: ( "com.apple.itunes", "com.apple.quicktime.udta" ) -1452383891 a96e616d -1455336876 a9415254 1631670868 61415254 -1451789708 a9777274 -1453233054 a9616c62 -1452838288 a9677270 -1452841618 a967656e 1953655662 74726b6e 1684632427 6469736b -1453039239 a9646179 -1453101708 a9636d74 1668311404 6370696c 1885823344 70676170 1953329263 746d706f -1451987089 a9746f6f com.apple.iTunes.iTun com.apple.iTunes.Enco 1668249202 636f7672 -1452508814 a96c7972 ==================== @nam @alb @ART 

When interpreted as 4 ASCII characters:

 © nam © ART a ART © wrt © alb © grp © gen trkn disk © day © cmt cpil pgap tmpo © too 

So, it seems that item.key is an item.key object, but the constants starting with AVMetadataiTunesMetadataKey... are NSString objects. What is the right way to get metadata? When I use [AVAsset commonMetadata] , the keys are also NSString objects, and comparing with the AVMetadataCommonKey... constants AVMetadataCommonKey... works as expected.

+6
source share
1 answer

The AVFoundation API is rather confusing when dealing with metadata.

The keys defined by the values ​​of AVMetadataiTunesMetadataKey * do not match the values ​​of the properties of the AVMetadataItem key. The AVMetadataiTunesMetadataKey * keys must be used with the API [AVMetadataItem metadataItemsFromArray:withKey:keySpace:AVMetadataKeySpaceiTunes] to filter metadata items using specific iTunes keys.

The keys and values ​​for AVMetadataItem depend on the exact resource file format. In addition to filtering keys using the above function, I suggest using the commonKey property, which provides a more general “key” property than others.

Modify your sample code to print commonKey along with the element value . Here are some examples:

  • commonKey - "title" - value - this is an NSString with the name of the song
  • commonKey is “artist” - meaning is NSString with a song artist
  • commonKey is 'albumName' - value is NSString with album name

Hope this helps!

+1
source

Source: https://habr.com/ru/post/949742/


All Articles