AVAsset 视频截图

2018-01-30  本文已影响242人  reallychao

使用AVFoundation框架可以生成视频缩略图,用到的类:

》》AVAsset:

用于获取多媒体的相关信息,如多媒体的画面和声音等。

》》AVURLAsset:

AVAsset的子类,用于根据NSURL生成AVAsset对象

》》AVAssetImageGenerator:

用于截取视频指定帧的动画

一般步骤:

1、根据视频的URLchuang见AVURLAsset对象

2、根据AVURLAsset对象创建AVAssetImageGenerator对象

3、调用AVAssetImageGenerator对象的copyCGImageAtTime:actualTime:error:来获取该视频指定时间点的视频截图

第一个参数:指定获取哪个时间点的视频截图,该参数是一个CMTime结构体:(CMTime. value/timescale = seconds)

CMTime CMTimeMake(
                int64_t value,        /*! @param value        Initializes the value field of the resulting CMTime. */
                int32_t timescale)    /*! @param timescale    Initializes the timescale field of the resulting CMTime. */
                            __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);

CMTime CMTimeMakeWithSeconds(
                Float64 seconds,      
          int32_t preferredTimeScale) 
                 __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);

获取CMTime相关函数:

CMTime CMTimeMake(
                int64_t value,        /*! @param value        Initializes the value field of the resulting CMTime. */
                int32_t timescale)    /*! @param timescale    Initializes the timescale field of the resulting CMTime. */
                            __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);

CMTime CMTimeMakeWithSeconds(
                Float64 seconds,      
          int32_t preferredTimeScale) 
                 __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);

第二个参数:获取截图的实际时间点(要用“&”传指针)

第三个参数:获取错误信息(要用“&”传指针)

视频截图函数

- (UIImage *)screenshotWithSeconds:(Float64)seconds{
    
    
    if (!_curPlayerItem) {
        return nil;
    }
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:self.curPlayerItem.asset];
    
    if (!generator) {
        return nil;
    }
    // 防止时间出现偏差
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    CMTime time = kCMTimeZero;
    if (seconds > 0) {
        CMTimeScale timeScale = self.curPlayerItem.asset.duration.timescale;
        time = CMTimeMakeWithSeconds(seconds, timeScale);
    }
    else
    {
        time = self.curPlayerItem.currentTime;
    }
    
    CMTime actualTime;
    NSError *error;
    CGImageRef cgImage = [generator copyCGImageAtTime:time
                                           actualTime:&actualTime
                                                error:&error];
    if (!cgImage) {
        return nil;
    }
    
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    CFRelease(cgImage);
    
    if (nil != error) {
        //BBAPlayerLog(@"screenshotWithSeconds:%@",error);
        return nil;
    }
    
    return image;
}
上一篇下一篇

猜你喜欢

热点阅读