iOS 中视频裁剪

/ 0评 / 0

App中要用到裁剪视频,功能需求比较简单,先来个获取四位随机数字的方法,这个主要是为了给视频命名用的:

- (NSString *)randomString {
    NSString *letters = @"0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: 4];
    for (int i = 0; i<4; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex:arc4random_uniform((int)[letters length])]];
    }
    return randomString;
}

先要拿到一个资源文件或者资源所在的本地地址转化为资源,这样就可以方便的使用系统方法了

AVAsset *asset = [AVAsset assetWithURL:videoUrl];

NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
if ([compatiblePresets containsObject:AVAssetExportPresetMediumQuality]) {
    //文件存放位置
    NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"/Videos"];

    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy_MM_dd_HH_mm_ss";
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.mp4",[formatter stringFromDate:[NSDate date]],[self randomString]]; //拼接个名字
    
    NSURL *furl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@",videoPath,fileName]];
    
    exportSession.outputURL = furl; //输出地址
    exportSession.outputFileType = AVFileTypeMPEG4;  //输出格式
    
    CMTime start = CMTimeMakeWithSeconds(0, asset.duration.timescale); //开始时间
    CMTime duration = CMTimeMakeWithSeconds(10, asset.duration.timescale); //截取多长
    exportSession.timeRange = CMTimeRangeMake(start, duration); //截取的时间信息
    

    [self.exportSession exportAsynchronouslyWithCompletionHandler:^{ //开始裁剪
        switch ([self.exportSession status]) {
            case AVAssetExportSessionStatusFailed:
                //失败
                NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                break;
            case AVAssetExportSessionStatusCancelled:
                //取消
                NSLog(@"Export canceled");
                break;
            default:
                NSLog(@"NONE");
                NSString *movieUrl = [NSString stringWithFormat:@"%@/%@",videoPath,fileName];
                NSLog(@"===视频路径为=====%@",movieUrl);
                //这里拿到的数据就可以上传了
                NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:movieUrl]];
                
                break;
        }
    }];
}

这样就可以完成简单的视频裁剪了。

评论已关闭。