Ios视频截取功能,常用到的AVFoundation下的类:
·AVURLAsset:AVAsset的子类,主要用于获取多媒体的信息,比如音视频的类型、时长、每秒帧数,还可以用来获取视频指定位置的缩略图。
·AVMutableCompositionTrack:视频和音频的采集都需要通过这个类。
·AVMutableComposition:AVAsset的子类,无法直接通过这个类,获取视频的基本信息。慢动作视频的AVAsset是AVMutableComposition类型,无法直接获取视频的URL。
·CMTime:专门用于标示视频时间的结构体。
·AVAssetExportSession:用户合并你采集的视频和音频,最终会保存为一个新的文件。可以设置文件的输出类型、路径,以及合并的状态AVAssetExportSessionStatus。
第一步:
获取需要截取视频的AVAsset。普通类型和延时摄影类型视频的AVAsset是AVURLAsset类,使用时可通过AVURLAsset获取视频资源的URL,可通过URL创建AVAsset,或者直接获取;
[[PHImageManager defaultManager]requestAVAssetForVideo:modal.phAsset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
asset;
}];
慢动作视频的AVAsset是AVMutableComposition类型,无法直接获取视频的URL或AVasset,可通过AVPlayerItem获取avasset:
[[PHImageManager defaultManager]requestPlayerItemForVideo:modal.phAsset options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
playerItem.asset
}];
第二步:
获取截取的起始点(以截取1秒到5秒的视频为例)
CMTime start = CMTimeMakeWithSeconds(1, self.asset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds(4, self.asset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
第三步:
创建AVAssetExportSession对象
+(void)cutVideoWithAsset:(AVAsset*)asset captureVideoWithRange:(CMTimeRange)videoRange completion:(void(^)(NSURL* outputUrl , long long fileSize,NSError * error))completionHandle{
AVAssetExportSession * exportSession = [[AVAssetExportSession alloc]
initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
NSArray * compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
//混合后的视频输出路径
NSString * urlString = [self createOutputFileUrl];
NSURL * outPutUrl = [NSURL fileURLWithPath:urlString];
exportSession.outputURL = outPutUrl;
exportSession.outputFileType = AVFileTypeMPEG4;
//输出文件是否网络优化
exportSession.shouldOptimizeForNetworkUse = YES;
//截取的起始点
exportSession.timeRange = videoRange;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
int status = exportSession.status;
switch (status) {
case AVAssetExportSessionStatusCompleted:
{
}
break;
case AVAssetExportSessionStatusFailed:
{
}
default:
break;
}
}];
}
}
//创建输出路径
+(NSString*)createOutputFileUrl{
double timeInterval = [NSDate timeIntervalSinceReferenceDate];
NSString *typeStrWithFileName = [NSString stringWithFormat:@"%.0f.mp4",timeInterval];
NSString *tmpPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library/"] stringByAppendingString:@"videos"];
NSString * outputUrl = [tmpPath stringByAppendingPathComponent:typeStrWithFileName];
if (![[NSFileManager defaultManager]fileExistsAtPath:tmpPath]) {
[[NSFileManager defaultManager]createDirectoryAtPath:tmpPath withIntermediateDirectories:YES attributes:nil error:nil];
}
return outputUrl;
}