在 tableviewcell 中显示视频的缩略图

display thumbnails of video in tableviewcell

这是我的代码,运行良好。我在这里访问我的 tableview 中的视频数组.....

这是我的一系列视频,视频在我的捆绑包中...

        - (void)viewDidLoad {
            [super viewDidLoad];
             videos = [[NSMutableArray alloc] initWithObjects:
                         @"video 1",
                         @"video 2",

                         nil];
        }

正在访问表格视图中的视频.....

        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            static NSString *CellIdentifier = @"Cell";

            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        NSIndexPath *index ;

        index = [self.table indexPathForCell:cell];
        NSLog(@"%@----hello",indexPath);

// taking path of video from bundle 
        NSString *filePath = [[NSBundle mainBundle]pathForResource:[videos objectAtIndex:indexPath.row] ofType:@"mp4"];

//declare nsurl and mpmoviplayer globally..
        movieURL = [NSURL fileURLWithPath:filePath];


  // <converting image in thumbnail...
        AVAsset* videoAsset = [AVAsset assetWithURL:movieURL];

        AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:videoAsset];

        Float64 durationSeconds = CMTimeGetSeconds([videoAsset duration]);
        CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
        NSError* error = nil;
        CMTime actualTime;

        //generating image...
        CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];


   // show image in uiimage of tableviewcell....
        cell.imageView.image=[UIImage imageWithCGImage:halfWayImage];
        cell.textLabel.text= [videos objectAtIndex:indexPath.row];


        return cell;

        }

正在通过 Segue 访问其他视图中的视频......

        - (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
                if ([segue.identifier isEqualToString:@"showDetailsSeg"]) {

//playing video in other view controller....

                    [[player view] setFrame: self.view.frame];
                    [self.view addSubview: [player view]];

                    [self presentMoviePlayerViewControllerAnimated:player];

//using sequel for destination controller
                    [segue destinationViewController] ;
               }
        }

完成....

如果"video"是ALAsset的实例,那么你可以使用-(CGImageRef)thumbnail方法:

UIImage* thumb = [UIImage imageWithCGImage:[video thumbnail]];

如果使用AVAsset呈现视频对象,可以使用AVAssetImageGenerator to get image at specific time and use this image to generate thumb

你可以这样做:

dispatch_async(dispatch_get_main_queue(), ^{
    NSURL* urlToVideo = [NSURL URLWithString:@"file://localPathToVideo"];
    AVAsset* videoAsset = [AVAsset assetWithURL:urlToVideo];

    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:videoAsset];

    Float64 durationSeconds = CMTimeGetSeconds([videoAsset duration]);
    CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
    NSError* error = nil;
    CMTime actualTime;

    CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

    UIImage* resultUIImage = nil;
    if (halfWayImage != NULL) {
        resultUIImage = [UIImage imageWithCGImage:halfWayImage];

        CGImageRelease(halfWayImage);

        //resize image (use some code for resize)
        //<>
        //TODO: call some method to resize image
        UIImage* resizedImage = resultUIImage;
        //<>

        dispatch_async(dispatch_get_main_queue(), ^{
            //TODO: set resized image to destination
            //if(cell.asset == videoAsset)
            //{
            //   cell.thumb.image = resizedImage
            //}
        });         
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //TODO: do something if you can't generate preview.
        });
    }
});

UPD


说明,为什么开发者应该使用 ALAsset 或 AVAsset 在应用程序中呈现视频。视频是结构复杂的二进制文件,要访问视频数据,您可以编写自己的库,并使用您的方法从视频中生成缩略图。但是 iOS SDK 提供了一些处理视频的方法。该 SDK 包含 ALFoundation 框架,它允许在任何路径(在您认为在 Documents 目录中)处理视频,您只需要知道视频 URL(或本地路径)。如果您从 AssetsLibrary 获取视频(照片),那么您就有了 ALAsset(展示了图书馆中的一些项目),ALAsset 的类型为 属性 和 thumb 属性,并且资产为 URL。


要使用 ALFoundation,您应该导入此库:

@import AVFoundation;

要使用 AssetsLibrary,您应该导入此库:

@import AssetsLibrary;

此外,我认为您应该在编写代码之前阅读提供的链接。

显示视频缩略图您可以执行以下操作,我添加了 Swift 和 Objective-C 代码来生成视频缩略图。

Swift 3.X 和 4.0

do {
                let asset = AVURLAsset(url: videoURL as! URL)
                let imageGenerator = AVAssetImageGenerator(asset: asset)
                imageGenerator.appliesPreferredTrackTransform = true
                let cgImage = try imageGenerator.copyCGImage(at: CMTimeMake(3, 1), actualTime: nil)
                let thumbnail = UIImage(cgImage: cgImage)
                imgView.image = thumbnail
            }catch{
                print("Error is : \(error)")
            }

其中 videoURL 是您的视频文件的路径。

Objective-C代码:

-(UIImage *)generateThumbImage : (NSString *)filepath
{
    NSURL *url = [NSURL fileURLWithPath:filepath];

    AVAsset *asset = [AVAsset assetWithURL:url];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    CMTime time = [asset duration];
    time.value = 1000; //Time in milliseconds
    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);  // CGImageRef won't be released by ARC

    return thumbnail;
}