压缩视频

2020-09-21 09:38:52 浏览数 (1)

问题

对视频进行压缩并输出

解决方案

代码语言:javascript复制
/// 压缩视频文件
-(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];
    }];
}

0 人点赞