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

2021-08-14  本文已影响0人  浅_若清风

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:@"本地视频的路径"];
上一篇下一篇

猜你喜欢

热点阅读