在最近的项目中,涉及到视频上传,在网上找了下资料,这里整理下来希望对大家有帮助,这里简短谈下整个流程;
1. 创建保存该视频的文件夹
- (void)createVideoFolderIfNotExist{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *folderPath = [path stringByAppendingPathComponent:videoFolders];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir = NO;
BOOL isDirExist = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
if(!(isDirExist && isDir)) {
BOOL create = [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
if(!create){
NSLog(@"创建保存视频文件夹失败");
}
}
}
2. 视频录制完以后保存的视频
- (NSString *)getVideoSaveFilePathString{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
path = [path stringByAppendingPathComponent:videoFolders];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@".mov"];
return fileName;
}
3. 根据以上两个方法,最后合成为 mp4
- (NSString *)getVideoMergeFilePathString{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
path = [path stringByAppendingPathComponent:videoFolders];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *nowTimeStr = [formatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
NSString *fileName = [[path stringByAppendingPathComponent:nowTimeStr] stringByAppendingString:@"merge.mp4"];
return fileName;
}
主要的代码
//根据设备输出获得连接
AVCaptureConnection *captureConnection=[self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
//根据连接取得设备输出的数据
if (![self.captureMovieFileOutput isRecording]) {
// shootBt.backgroundColor = UIColorFromRGB(0xfa5f66);
//预览图层和视频方向保持一致
captureConnection.videoOrientation=[self.captureVideoPreviewLayer connection].videoOrientation;
[self.captureMovieFileOutput startRecordingToOutputFileURL:[NSURL fileURLWithPath:[self getVideoSaveFilePathString]] recordingDelegate:self];
#视频压缩
NSString *path = [self getVideoMergeFilePathString];
NSURL *mergeFileURL = [NSURL fileURLWithPath:path];
AVMutableVideoCompositionInstruction *mainInstruciton = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
mainInstruciton.timeRange = CMTimeRangeMake(kCMTimeZero, totalDuration);
mainInstruciton.layerInstructions = layerInstructionArray;
AVMutableVideoComposition *mainCompositionInst = [AVMutableVideoComposition videoComposition];
mainCompositionInst.instructions = @[mainInstruciton];
mainCompositionInst.frameDuration = CMTimeMake(1, 100);
mainCompositionInst.renderSize = CGSizeMake(renderW, renderW*preLayerHWRate);
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
exporter.videoComposition = mainCompositionInst;
exporter.outputURL = mergeFileURL;
exporter.outputFileType = AVFileTypeMPEG4; //mp4
exporter.shouldOptimizeForNetworkUse = YES;
[exporter exportAsynchronouslyWithCompletionHandler:^{
if ([exporter status] == AVAssetExportSessionStatusCompleted) {
dispatch_async(dispatch_get_main_queue(), ^{
################# 这里的二进制就是上传的东西了##################
NSData *data = [NSData dataWithContentsOfURL:exporter.outputURL];
}];
上传的方法
NSString *imageStr = @"公司接口";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
NSMutableDictionary *param = [NSMutableDictionary dictionary];
[manager POST:imageStr parameters:param constructingBodyWithBlock:^(id formData) {
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"file"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]
*/
[formData appendPartWithFileData:datas name:@"video" fileName:@"videosNames" mimeType:@"video/mp4"];
// [formData appendPartWithFormData:datas name:@"video"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *cashDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",cashDic[@"remark"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"faile ----->%@",error);
}];
感谢:https://blog.csdn.net/whjay520/article/details/53440369