当前位置: 首页 > news >正文

iOS视频压缩存储至本地并上传至服务器-b

最近做了一个项目,我把其中的核心功能拿出来和大家分享一下,重点还是自己梳理一下。

这里关于视频转码存储我整理了两个方法,这两个方法都是针对相册内视频进行处理的。

1、该方法没有对视频进行压缩,只是将视频原封不动地从相册拿出来放到沙盒路径下,目的是拿到视频的NSData以便上传

这里我传了一个URL,这个URL有点特别,是相册文件URL,所以我说过只针对相册视频进行处理

//将原始视频的URL转化为NSData数据,写入沙盒     
+ (void)videoWithUrl:(NSString *)url withFileName:(NSString *)fileName     {           
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];          
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{            
        if (url) {              
            [assetLibrary assetForURL:[NSURL URLWithString:url] resultBlock:^(ALAsset *asset) {             
            ALAssetRepresentation *rep = [asset defaultRepresentation];            
            NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];            NSString *imagePath = [NSString stringWithFormat:@"%@/Image", pathDocuments];            NSString *dbFilePath = [imagePath stringByAppendingPathComponent:fileName];            char const *cvideoPath = [dbFilePath UTF8String];             
            FILE *file = fopen(cvideoPath, "a+");            
            if (file) {                
                const int bufferSize = 11024 * 1024;                // 初始化一个1M的buffer                 
                Byte *buffer = (Byte*)malloc(bufferSize);                
                NSUInteger read = 0, offset = 0, written = 0;                
                NSError* err = nil;                
                if (rep.size != 0)                 {                    
                    do {                         
                        read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];                         
                        written = fwrite(buffer, sizeof(char), read, file);                         
                        offset += read;                     
                     } while (read != 0 && !err);//没到结尾,没出错,ok继续                 
                }                // 释放缓冲区,关闭文件                 
                free(buffer);                 
                buffer = NULL;                 
                fclose(file);                 
                file = NULL;             
            }         
        } failureBlock:nil];     
     } 
  });

}

2、推荐使用该方法,该方法对视频进行压缩处理,压缩的程度可调

这里我传的是模型过去,将我的URL带过去的,然后压缩完毕用模型把NSData带出来,数据大家根据自己需求自由发挥

+ (void) convertVideoWithModel:(RZProjectFileModel *) model {     
    model.filename = [NSString stringWithFormat:@"%ld.mp4",RandomNum];    //保存至沙盒路径    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];    NSString *videoPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];     
    model.sandBoxFilePath = [videoPath stringByAppendingPathComponent:model.filename];    //转码配置    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:model.assetFilePath options:nil];    AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];     
    exportSession.shouldOptimizeForNetworkUse = YES;     
    exportSession.outputURL = [NSURL fileURLWithPath:model.sandBoxFilePath];     
    exportSession.outputFileType = AVFileTypeMPEG4;     
    [exportSession exportAsynchronouslyWithCompletionHandler:^{          
        int exportStatus = exportSession.status;        
        RZLog(@"%d",exportStatus);         
        switch (exportStatus)         {            
            case AVAssetExportSessionStatusFailed:             
            {                
                // log error to text view                
                NSError *exportError = exportSession.error;                
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);                
                break;             
            }            
            case AVAssetExportSessionStatusCompleted:             
            {                
                RZLog(@"视频转码成功");                
                NSData *data = [NSData dataWithContentsOfFile:model.sandBoxFilePath];                 
                model.fileData = data;             
            }         
        }         
        }];  
}

在这里你可以修改压缩比例,苹果官方都封装好了,根据需求调整

AVAssetExportSession *exportSession= [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetMediumQuality];

在这里修改输出类型,正常情况下选MP4不会有什么问题的

exportSession.outputFileType = AVFileTypeMPEG4;

Mark一下图片压缩用这个,image是图片,0.4是比例,大小可调

model.fileData = UIImageJPEGRepresentation(image, 0.4);

这样你就很愉快地拿到转码过后的NSData了,然后播放一下试试

MPMoviePlayerViewController* playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:sandBoxFilePath]]; 
[superVC presentViewController:playerView animated:YES completion:nil];

备注一下

可以发现我这里使用了沙盒存储,在下一节我整理一下用代码管理应用沙盒。

更新

最近发现好多人联系我,问我要Demo,最近我也整理了一下,目前挂在github上,望大神们指正。https://github.com/Snoopy008/SelectVideoAndConvert

相关文章:

  • js实现水平伸缩菜单
  • knockout中computed和pureComputed的区别
  • java Nio零散知识点整理
  • Linux命令之dos2unix - 将DOS格式文本文件转换成UNIX格式
  • 直播相关知识收集
  • 每日一题_Python.利用yield生成器实现协程下的tps透明传输CS测试
  • Tomcat 容器 POI 生成 Excel 文件 可能会使用到 temp 临时文件夹
  • Windows10 查看 自己笔记本的电池状况
  • 二维码生成工厂
  • 解决Idea创建maven-archetype-webapp项目无java目录的问题
  • 项目笔记之订单号生成规则以及方法,第一篇!
  • 用好阿里云分析型数据库大存储实例,大幅降低大数据应用成本
  • python 测试驱动开发的简单例子
  • win10 + uefi
  • Nginx负载均衡的详细配置及使用案例详解.
  • [nginx文档翻译系列] 控制nginx
  • 2017年终总结、随想
  • 2019.2.20 c++ 知识梳理
  • Apache的基本使用
  • Git 使用集
  • JavaScript 基础知识 - 入门篇(一)
  • Java多线程(4):使用线程池执行定时任务
  • LeetCode算法系列_0891_子序列宽度之和
  • mysql 5.6 原生Online DDL解析
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • 电商搜索引擎的架构设计和性能优化
  • 猴子数据域名防封接口降低小说被封的风险
  • 记录一下第一次使用npm
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 前端每日实战:70# 视频演示如何用纯 CSS 创作一只徘徊的果冻怪兽
  • 前端面试之CSS3新特性
  • 收藏好这篇,别再只说“数据劫持”了
  • 微信支付JSAPI,实测!终极方案
  • 第二十章:异步和文件I/O.(二十三)
  • 积累各种好的链接
  • ​2020 年大前端技术趋势解读
  • ​ArcGIS Pro 如何批量删除字段
  • ​什么是bug?bug的源头在哪里?
  • ​一些不规范的GTID使用场景
  • $emit传递多个参数_PPC和MIPS指令集下二进制代码中函数参数个数的识别方法
  • (4.10~4.16)
  • (java版)排序算法----【冒泡,选择,插入,希尔,快速排序,归并排序,基数排序】超详细~~
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (十一)c52学习之旅-动态数码管
  • (数据结构)顺序表的定义
  • .bat批处理(一):@echo off
  • .NET MVC第五章、模型绑定获取表单数据
  • .net 开发怎么实现前后端分离_前后端分离:分离式开发和一体式发布
  • .Net通用分页类(存储过程分页版,可以选择页码的显示样式,且有中英选择)
  • .net项目IIS、VS 附加进程调试
  • .NET中的Exception处理(C#)
  • .xml 下拉列表_RecyclerView嵌套recyclerview实现二级下拉列表,包含自定义IOS对话框...
  • /var/lib/dpkg/lock 锁定问题
  • [bzoj 3534][Sdoi2014] 重建
  • [C#][opencvsharp]opencvsharp sift和surf特征点匹配