IOS获取MP3的信息
//读取mp3里的信息
AudioFileID fileID;
AudioFileTypeID typeIdMP3 = kAudioFileMP3Type;
OSStatus status = noErr;
//读取mp3文件
status = AudioFileOpenURL((__bridge CFURLRef)fileURL, kAudioFileReadPermission, typeIdMP3, &fileID);
if (status != noErr) {
NSLog(@”AudioFileOpenURL Failure”);
}
// ID3,一般是位于一个mp3文件的开头或末尾的若干字节内,附加了关于该mp3的歌手,标题,专辑名称,年代,风格等信息,该信息就被称为ID3信息,ID3信息分为两个版本,v1和v2版。 其中:v1版的ID3在mp3文件的末尾128字节,以TAG三个字符开头,后面跟上歌曲信息。 v2版一般位于mp3的开头,可以存储歌词,该专辑的图片等大容量的信息。
UInt32 id3DataSize = 0;
status = AudioFileGetPropertyInfo(fileID, kAudioFilePropertyID3Tag, &id3DataSize, NULL);
if (status != noErr) {
NSLog(@”读id3DataSize失败,没有附加信息”);
}
NSLog(@”id3DataSize: %ld”,id3DataSize);
//唱片信息
NSDictionary *propertyInfo = nil;
UInt32 piDataSize = sizeof(propertyInfo);
status = AudioFileGetProperty(fileID, kAudioFilePropertyInfoDictionary, &piDataSize, &propertyInfo);
if (status != noErr) {
NSLog(@”读取唱片信息失败”);
}
NSLog(@”propertyInfo: %@”,propertyInfo);
//唱片封面 这里获取到的图片数据是空的,暂时不知道为什么,建议使用方法2,简单
CFDataRef albumPic = nil;
UInt32 albumPicDataSize = sizeof(albumPic);
status = AudioFileGetProperty(fileID, kAudioFilePropertyAlbumArtwork, &albumPicDataSize, &albumPic);
if (status != noErr) {
NSLog(@”读取唱片封面失败”);
}
//获取专辑名称
NSString *album = propertyInfo[@”album”];
NSString *artist = propertyInfo[@”artist”];
NSString *title = propertyInfo[@”title”];
NSString *year = propertyInfo[@”year”];
CZMP3Info *mp3Info = [[CZMP3Info alloc] init];
mp3Info.album = album;
mp3Info.artist = artist;
mp3Info.title = title;
mp3Info.year = year;
mp3Info.albumArtwork = (__bridge NSData *)albumPic;
方法2:
AVURLAsset *assest = [AVURLAsset URLAssetWithURL:fileURL options:nil];
CZMP3Info *mp3Info = [[CZMP3Info alloc] init];
NSLog(@”%@”,assest.lyrics);
for (NSString *key in [assest availableMetadataFormats]) {
for (AVMetadataItem *item in [assest metadataForFormat:key]) {
NSString *commonKey = item.commonKey;
if ([commonKey isEqualToString:@”artist”]) {//歌手
mp3Info.artist = (NSString *)item.value;
}else if([commonKey isEqualToString:@”albumName”]){//专辑名称
mp3Info.album = (NSString *)item.value;
}else if([commonKey isEqualToString:@”title”]){//歌曲名
mp3Info.title = (NSString *)item.value;
}else if ([commonKey isEqualToString:@”artwork”]){
NSDictionary *artworkDict = (NSDictionary *)item.value;
NSData *image = [artworkDict objectForKey:@”data”];
mp3Info.albumArtwork = image;
}
}
}
CMTime durationTime = assest.duration;
CGFloat duration = CMTimeGetSeconds(durationTime);