压缩视频

作者: freesan44 | 来源:发表于2020-09-17 10:44 被阅读0次

    问题

    对视频进行压缩并输出

    解决方案

    /// 压缩视频文件
    -(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];
        }];
    }
    

    相关文章

      网友评论

        本文标题:压缩视频

        本文链接:https://www.haomeiwen.com/subject/wfhlyktx.html