您的位置:首页 > 移动开发 > IOS开发

iOS视频播放列表中默认展示图如何获取

2017-08-02 15:42 381 查看
1.让后台直接返回一个图片的URL地址,直接展示。这种方法是用的比较多的,比较通用的方法。

2.根据后台传过来的视频URL,iOS端自己截取视频的某一帧做为展示图。(此方法耗时比较严重,界面会卡顿)。

在此,单独说说第二种方法。

获取视频某一帧的代码,如下:

// 获取视频某一帧,返回UIImage
- (UIImage*) getVideoPreViewImage:(NSURL *)path
{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

assetGen.appliesPreferredTrackTransform = YES;
//视图时间,想要截取对应时间的帧,可以更改这个参数
CMTime time = CMTimeMakeWithSeconds(2.0, 600);
NSError *error = nil;
CMTime actualTime;//可不设置,传NULL
CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return videoImage;
}


如果视频列表比较多,直接使用这个方法,界面肯定会卡,这时需要放到异步线程去处理,获得图片后再回到主线程更新界面。大致方法如下:

__weak typeof(self) weakSelf = self;
//异步请求
dispatch_async(dispatch_get_global_queue(0,0), ^{
for (int i = 0; i < 10; i++) {

UIImage * image = [weakSelf getVideoPreViewImage:[NSURL URLWithString:videoUrl]];
if (image != nil) {
[weakSelf.videoPreImageViewArray addObject:image];
//更新UI,回到主线程
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.tableView reloadData];
});
}
}
});


我这里将请求得到的图片存到了videoPreImageViewArray数组中,在tableView的代理方法中处理一下,当请求到图片之后再进行展示

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

static NSString *indentify = @"VieoShowCell";

VieoShowCell *cell = [tableView dequeueReusableCellWithIdentifier:indentify];

if (cell == nil) {

cell = [[[NSBundle mainBundle] loadNibNamed:@"VieoShowCell" owner:self options:nil] lastObject];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//重点看这里
if (self.videoPreImageViewArray.count > indexPath.row) {
cell.imageVedioView.image = self.videoPreImageViewArray[indexPath.row];
}

return cell;
}


以上就是大概的处理方法,虽然加到了异步线程,获取视频中某一帧还是有些慢,但是,不会出现卡顿了。 如果大家有更好的处理方法,欢迎沟通交流。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: