Is there a way to extract embedded image data from an mp3 in ios

纵饮孤独 提交于 2019-12-09 19:15:37

问题


I understand that mp3s sometimes contain album artwork (in my case, I'm working with podcast files). Is there a way in iOS to extract the image data from an mp3 file?


回答1:


MP3s, including podcasts, do often have embedded metadata, including artwork. The easiest way to get the embedded metadata (for MP3s not in the iTunes library) is through the AVAsset class. If you are trying to get metadata over a network use the AVURLAsset instead, but accessing the metadata is the same with either.

AVAsset has an NSArray property named commonMetadata which contains instances of the class AVMetadataItem. You can iterate over this array to find the element with the commonKey of(usually) "artwork" The value property of this AVMetadataItem should be an NSDictionary of data about the artwork. Within this dictionary you will find the key "data" which should contain data you can use to construct a UIImage. This is quite nested and this description is admittedly confusing. So here is a code example.

NSURL *url = <# url of resource here #>;
AVAsset *asset = [AVAsset assetWithURL:url];
for (AVMetadataItem *metadataItem in asset.commonMetadata) {
    if ([metadataItem.commonKey isEqualToString:@"artwork"]){
        NSDictionary *imageDataDictionary = (NSDictionary *)metadataItem.value;
        NSData *imageData = [imageDataDictionary objectForKey:@"data"];
        UIImage *image = [UIImage imageWithData:imageData];
         // Display this image on my UIImageView property imageView
        self.imageView.image = image;
    }
}

Again this is a very simple example of how to load from a local resource; If you are loading this over a network you should use an AVURLAsset. Also be careful of the blocking nature of this call.




回答2:


Take a look at Apple's sample AddMusic project and you'll see how they get the album artwork via MPMediaItem & MPMediaItemArtwork objects.




回答3:


-(UIImage *)getMP3Pic:(NSURL *)url
{
    AVAsset *asset = [AVAsset assetWithURL:url];
    for (AVMetadataItem *metadataItem in asset.commonMetadata) {
       if ([metadataItem.commonKey isEqualToString:@"artwork"]){
            return [UIImage imageWithData:(NSData *)metadataItem.value];
       }
    }
}


来源:https://stackoverflow.com/questions/7814248/is-there-a-way-to-extract-embedded-image-data-from-an-mp3-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!