ios获取本地视频缩略图和时长

1.获取视频的时长
创建一个model类来创建方法

//model.h文件中实现
+ (CGFloat)getTimeFromVideoPath:(NSString *)filePath;
//model.m文件中实现
+ (CGFloat)getTimeFromVideoPath:(NSString *)filePath
{
    AVURLAsset * asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:filePath]];
    CMTime   time = [asset duration];
    CGFloat seconds = time.value/time.timescale;
    return seconds;
}

2.获取视频的缩略图

//model.h文件中实现
+ (UIImage *)getScreenShotImageFromVideoPath:(NSString *)filePath;
//model.m文件中实现
+ (UIImage *)getScreenShotImageFromVideoPath:(NSString *)filePath
{
    //视频路径URL
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *shotImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return shotImage;
}

上述代码中filePath为本地视频的路径,CMTime为C的一个结构体,duration为AVAsset中表示时长的属性值。value和timescale都是CMTime结构体中的值,其中value 表示当前的CMTime 的值,timescale 当前的CMTime 的时间刻度,time.value/time.timescale即为时长,结构函数CMTimeMakeWithSeconds包含两个参数,第一个参数表示当前的时间,第二个参数表示每秒的帧数,使用copyCGImageAtTime方法来获取指定时间段time的截图(例如代码中设置设置为0,即表示截取第一秒的界面作为缩略图)。
3.VC中调用

//视频时长
CGFloat time = [PublicModel getTimeFromVideoPath:@"本地视频的路径"];
//缩略图
UIImage *image = [PublicModel getScreenShotImageFromVideoPath:@"本地视频的路径"];
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容