1. 程式人生 > >獲取音視訊檔案AVMetadata資料

獲取音視訊檔案AVMetadata資料

做音樂播放器應用有時候需要獲取音樂檔案的一些資料資訊,比如該音樂檔案中的封面圖片,藝人名,專輯名等,如何獲取呢?本人拋磚引玉,寫一個獲取封面圖片的類供大家參考.

複製程式碼
//
//  AVMetadataInfo.h
//
//  http://home.cnblogs.com/u/YouXianMing/
//
//  Copyright (c) 2014年 Y.X. All rights reserved.
//

#import <Foundation/Foundation.h>

#warning 需要引入AVFoundation.framework

@interface AVMetadataInfo : NSObject

/** 獲取音視訊檔案的Metadata資訊(可以獲取到mp3以及m4a的相關資訊) *AVMetadataCommonKeyArtwork這個引數是可以換的,換不同的引數可以取得不同的值 *[注意]此方法中用到了訊號量將非同步操作轉換成了同步操作,儘量在主執行緒中使用 @param fileURL 檔案的URL地址 @return 一個包含了相關內容的字典 */ + (NSDictionary *)dataInfoFromFileURL:(NSURL *)fileURL; @end
複製程式碼 複製程式碼
//
//  AVMetadataInfo.m
//
//  http://home.cnblogs.com/u/YouXianMing/
// // Copyright (c) 2014年 Y.X. All rights reserved. // #import "AVMetadataInfo.h" #import <AVFoundation/AVFoundation.h> @implementation AVMetadataInfo + (NSDictionary *)dataInfoFromFileURL:(NSURL *)fileURL { // 建立字典 NSMutableDictionary *dic = [NSMutableDictionary dictionary]; // 建立訊號量(將非同步變成同步)
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); AVAsset *asset = [AVURLAsset URLAssetWithURL:fileURL options:nil]; [asset loadValuesAsynchronouslyForKeys:@[@"commonMetadata"] completionHandler:^{ // 傳送訊號量 dispatch_semaphore_signal(semaphore); }]; // 無限等待 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // 獲取資料 NSArray *artworks = [AVMetadataItem metadataItemsFromArray:asset.commonMetadata withKey:AVMetadataCommonKeyArtwork keySpace:AVMetadataKeySpaceCommon]; for (AVMetadataItem *item in artworks) { if ([item.keySpace isEqualToString:AVMetadataKeySpaceID3]) { NSDictionary *dict = [item.value copyWithZone:nil]; // 獲取圖片 UIImage *image = [UIImage imageWithData:[dict objectForKey:@"data"]]; [dic setObject:image forKey:@"Artwork"]; } if ([item.keySpace isEqualToString:AVMetadataKeySpaceiTunes]) { // 獲取圖片 UIImage *image = [UIImage imageWithData:[item.value copyWithZone:nil]]; [dic setObject:image forKey:@"Artwork"]; } } return [NSDictionary dictionaryWithDictionary:dic]; } @end
複製程式碼

引入標頭檔案,然後

沒有然後了,就是這麼簡單.想要獲取其他資訊,請讀者自行修改,很簡單的.