前言
很多自定义播放器,和自定义多选相册的图片都是需要先获取系统图片库中的所有图片资源或者视屏资源 ,所使用的核心方法就是AssetsLibrary框架里的ALAssetsLibrary。
事先准备
-
导入系统类库
-
封装一个实体model类
#import <AssetsLibrary/AssetsLibrary.h> @interface AlbumVideoInfo : NSObject @property(nonatomic, copy) NSString *name; @property(nonatomic, assign) long long size; //Bytes @property(nonatomic, strong) NSNumber *duration; @property(nonatomic, copy) NSString *format; @property(nonatomic, strong) UIImage *thumbnail; @property (nonatomic, strong) NSURL *videoURL; @end @implementation AlbumVideoInfo @end
取本地视屏资料 、播放:
{
_albumVideoInfos = [[NSMutableArray alloc]initWithCapacity:0];
[self loadVideos];
}
- (void)loadVideos{
ALAssetsLibrary *library1 = [[ALAssetsLibrary alloc] init];
[library1 enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
#获取所有video资源,当然也可以获取所有图片资源,本地语音备忘录中的语音是无法获取的,
#曾经努力了很久也无法获得,如果知道怎么获取的朋友,一定要告诉我下,多谢。
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
AlbumVideoInfo *videoInfo = [[AlbumVideoInfo alloc] init];
#视屏的封页图片
videoInfo.thumbnail = [UIImage imageWithCGImage:result.thumbnail];
videoInfo.videoURL = result.defaultRepresentation.url;
#视频的时长
videoInfo.duration = [result valueForProperty:ALAssetPropertyDuration];
videoInfo.name = [self getFormatedDateStringOfDate:[result valueForProperty:ALAssetPropertyDate]];
videoInfo.size = result.defaultRepresentation.size; //Bytes
videoInfo.format = [result.defaultRepresentation.filename pathExtension];
[_albumVideoInfos addObject:videoInfo];
}
}];
} else {
//没有更多的group时,即可认为已经加载完成。
NSLog(@"after load, the total alumvideo count is %ld",_albumVideoInfos.count);
for (int i = 0; i<_albumVideoInfos.count; i++) {
AlbumVideoInfo *videoInfo = _albumVideoInfos[i];
NSLog(@"%@ ",videoInfo.duration);
BaitiaoImageV.image = videoInfo.thumbnail;
}
dispatch_async(dispatch_get_main_queue(), ^{
// [self showAlbumVideos];
});
}
} failureBlock:^(NSError *error) {
NSLog(@"Failed.");
}];
}
//将创建日期作为文件名
-(NSString*)getFormatedDateStringOfDate:(NSDate*)date{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"]; //注意时间的格式:MM表示月份,mm表示分钟,HH用24小时制,小hh是12小时制。
NSString* dateString = [dateFormatter stringFromDate:date];
return dateString;
}
由于相册视频不能获取到绝对地址,故使用系统自带的MPMoviePlayerController,进行播放
if (!_moviePlayer) {
_moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:albumVideoInfo.videoURL];
}
else{ [_moviePlayer setContentURL:albumVideoInfo.videoURL];
}
获得所有系统资源后,就可以实现自己的自定义效果啦