压缩视频

时间:2022-07-25
本文章向大家介绍压缩视频,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

问题

对视频进行压缩并输出

解决方案

/// 压缩视频文件
-(void)videoCompressionWithUrl:(NSURL *)url
                        finish:(void(^)(NSURL * fileUrl))finishCallback
{
    
    NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
#ifdef DEBUG
    NSData * orgData = [NSData dataWithContentsOfURL:url];
    NSLog(@"原视频长度:%d MB",orgData.length/1024/1024);
#endif
    
    NSString *destFilePath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.MOV",[[[NSUUID UUID]UUIDString]substringToIndex:8]]];
    NSURL *destUrl = [NSURL fileURLWithPath:destFilePath];
    
    //将视频文件copy到沙盒目录中
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;
    [manager copyItemAtURL:url toURL:destUrl error:&error];
    
    //加载视频资源
    AVAsset *asset = [AVAsset assetWithURL:destUrl];
    //创建视频资源导出会话
    AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];
    //创建导出视频的URL
    NSString *resultPath = [docuPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.MOV",[[[NSUUID UUID]UUIDString]substringToIndex:8]]];
    session.outputURL = [NSURL fileURLWithPath:resultPath];
    //必须配置输出属性
    session.outputFileType = @"com.apple.quicktime-movie";
    //导出视频
    [session exportAsynchronouslyWithCompletionHandler:^{
       
#ifdef DEBUG
        NSData * resultData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resultPath]];
        NSLog(@"压缩后的视频长度:%d MB",resultData.length/1024/1024);
#endif
         NSLog(@"压缩后的视频地址为 %@",resultPath);
        if (finishCallback) {
            NSURL * resultPathUrl = [NSURL URLWithString:resultPath];
            finishCallback(resultPathUrl);
        }
         //删除沙盒中的高质量视频文件
        [manager removeItemAtPath:destFilePath error:nil];
    }];
}