一个视频自由设置时间,并裁剪成更短时间的视频。
示例代码如下:
+ (void)videoClippingWithFilePath:(NSString *)filePath start:(CGFloat)startTime end:(CGFloat)endTime complete:(void (^)(BOOL isSuccess, NSString *videoPath, Float64 videoDuration))complete
{
if (filePath == nil || filePath.length <= 0) {
if (complete) {
complete(NO, nil, 0.0);
}
} else {
NSURL *url = [NSURL fileURLWithPath:filePath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
// 裁剪保存路径
NSString *fileName = filePath.lastPathComponent;
NSString *fileType = fileName.pathExtension;
NSString *outputFileName = [NSString stringWithFormat:@"output.%@", fileType];
NSString *outputFilePath = [[filePath stringByReplacingOccurrencesOfString:fileName withString:@""] stringByAppendingPathComponent:outputFileName];
NSLog(@"fileName = %@, fileType = %@, outputFilePath = %@", fileName, fileType, outputFilePath);
NSURL *outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
//
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
exportSession.outputURL = outputFileUrl;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse = YES;
//
CMTime start = CMTimeMakeWithSeconds(startTime, asset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds((endTime - startTime), asset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
exportSession.timeRange = range;
//
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed: {
NSLog(@"裁剪失败:%@", [[exportSession error] description]);
if (complete) {
complete(NO, outputFilePath, endTime);
}
} break;
case AVAssetExportSessionStatusCancelled: {
if (complete) {
complete(NO, outputFilePath, endTime);
}
} break;
case AVAssetExportSessionStatusCompleted: {
if (complete) {
complete(YES, outputFilePath, endTime);
}
} break;
default: {
if (complete) {
complete(NO, outputFilePath, endTime);
}
} break;
}
}];
}
}
需要导入头文件 ‘#import <AVFoundation/AVFoundation.h>’