.....
视频拍摄
//调用系统录像
- (void)addTakeVideo
{
_imagePickerVc = [[UIImagePickerController alloc] init];
_imagePickerVc.delegate = self;
_imagePickerVc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
_imagePickerVc.allowsEditing = YES;
_imagePickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
//录制视频时长,默认10s
_imagePickerVc.videoMaximumDuration = MAXFLOAT;
_imagePickerVc.modalPresentationStyle=UIModalPresentationOverFullScreen;
//相机类型(拍照、录像...)字符串需要做相应的类型转换
_imagePickerVc.mediaTypes = @[(NSString *)kUTTypeMovie];
//视频上传质量
//UIImagePickerControllerQualityTypeHigh高清
//UIImagePickerControllerQualityTypeMedium中等质量
//UIImagePickerControllerQualityTypeLow低质量
//UIImagePickerControllerQualityType640x480
_imagePickerVc.videoQuality = UIImagePickerControllerQualityTypeHigh;
//设置摄像头模式(拍照,录制视频)为录像模式
_imagePickerVc.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
[self.window.rootViewController presentViewController :_imagePickerVc animated:NO completion:nil];
}
//视频压缩
NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"我获取到的未压缩前的视频大小是:%@", [NSString stringWithFormat:@"%.2f mb", [self getFileSize:[sourceURL path]]]);
if ([[NSString stringWithFormat:@"%.2f", [self getFileSize:[sourceURL path]]] integerValue]>=1024) {
UIWindow *window = [UIApplication sharedApplication].keyWindow;
MBProgressHUD *Hud = [[MBProgressHUD alloc] initWithView:window];
[window addSubview:Hud];
Hud.mode = MBProgressHUDModeText;
Hud.labelText = @"视频过大";
Hud.userInteractionEnabled = NO;
Hud.removeFromSuperViewOnHide = YES;
[Hud show:YES];
[Hud hide:YES afterDelay:2];
return;
}
//显示加载视图
[[UIApplication sharedApplication].keyWindow addSubview:self.videoHud];
NSURL *newVideoUrl ; //一般.mp4
NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名,以免重复,在测试的时候其实可以判断文件是否存在若存在,则删除,重新生成文件即可
[formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/tmp/output-%@.mp4", [formater stringFromDate:[NSDate date]]]];//这个是保存在app自己的沙盒路径里,后面可以选择是否在上传后删除掉。我建议删除掉,免得占空间。
//视频压缩
[self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
- (void)convertVideoQuailtyWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL completeHandler:(void (^)(AVAssetExportSession*))handler
{
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
// NSLog(resultPath);
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeMPEG4;
exportSession.shouldOptimizeForNetworkUse= YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusCancelled:
NSLog(@"AVAssetExportSessionStatusCancelled");
break;
case AVAssetExportSessionStatusUnknown:
NSLog(@"AVAssetExportSessionStatusUnknown");
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"AVAssetExportSessionStatusWaiting");
break;
case AVAssetExportSessionStatusExporting:
NSLog(@"AVAssetExportSessionStatusExporting");
break;
case AVAssetExportSessionStatusCompleted:
{
NSLog(@"我录制的视频时长为:%@",[NSString stringWithFormat:@"%.2f s", [self getVideoLength:outputURL]]);
NSLog(@"我压缩后的视频大小为:%@", [NSString stringWithFormat:@"%.2f mb", [self getFileSize:[outputURL path]]]);
UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, @selector(videoSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL);//这个是保存到手机相册
break;
}
case AVAssetExportSessionStatusFailed:
NSLog(@"AVAssetExportSessionStatusFailed");
break;
}
}];
}
OSS 阿里云 断点续传
//初始化OSS token
#pragma mark -- 阿里云客户端 OSS 客户端sts 临时token
- (void)initOSSClient{
uc_authcode *ucCode = [[uc_authcode alloc]init];
NSString *encryptionString = [ucCode getEncryptionString];
NSDictionary *callParamsDic = [[NSDictionary alloc]initWithObjectsAndKeys:@"ossStsbyram",@"action",nil];
[AFNetWorkTool post:NEW_USERADDRESS path:USERPATH encryptionString:encryptionString params:callParamsDic success:^(id responseObj) {
GJLog(@"%@",responseObj);
int nStautus = [[responseObj objectForKey:@"status"] intValue];
NSString *contentStr = [responseObj objectForKey:@"content"];
if (nStautus == 1) {
NSDictionary *dic = [responseObj objectForKey:@"data"];
_accessKeyId = [dic objectForKey:@"AccessKeyId"];
_accessKeySecret =[dic objectForKey:@"AccessKeySecret"];
_expiration =[dic objectForKey:@"Expiration"];
_securityToken = [dic objectForKey:@"SecurityToken"];
} else{
[self.view makeToast:contentStr];
}
} failure:^(NSError *error) {
}];
}
//设置阿里云token
[self xys_ALIYUNSend];
#pragma mark -- 设置阿里云token
- (void)xys_ALIYUNSend{
id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
OSSFederationToken * token = [OSSFederationToken new];
token.tAccessKey = _accessKeyId;
token.tSecretKey = _accessKeySecret;
token.tToken = _securityToken;
token.expirationTimeInGMTFormat = _expiration;
return token;
}];
OSSClientConfiguration * conf = [OSSClientConfiguration new];
conf.maxRetryCount = 2;
conf.timeoutIntervalForRequest = 30;
conf.timeoutIntervalForResource = 24 * 60 * 60;
client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential clientConfiguration:conf];
}
//阿里云断点续传
[self xys_ALIYUNsendVideo];
#pragma mark -- 断点续传
- (void)xys_ALIYUNsendVideo{
[self.view addSubview:self.videoHud];
[SingleManager shareManager].isResumableUpload = YES;
//阿里云视频上传的方法
__block NSString * recordKey;
NSURL *filePath = [SingleManager shareManager].videoURL;
NSString * bucketName = @"xys-app-file";
NSString * objectKey;
if (_uploadid == nil) {
objectKey = [self getObjectKey];
_uploadid = objectKey;
} else{
objectKey = _uploadid;
}
[[[[[[OSSTask taskWithResult:nil] continueWithBlock:^id(OSSTask *task) {
// 为该文件构造一个唯一的记录键
// NSURL * fileURL = [NSURL fileURLWithPath:filePath];
NSDate * lastModified;
NSError * error;
[filePath getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];
if (error) {
return [OSSTask taskWithError:error];
}
recordKey = [NSString stringWithFormat:@"%@-%@-%@-%@", bucketName, objectKey, [OSSUtil getRelativePath:[filePath absoluteString]], lastModified];
NSLog(@"recordKeyrecordKeyrecordKey-------%@",recordKey);
// 通过记录键查看本地是否保存有未完成的UploadId
NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
return [OSSTask taskWithResult:[userDefault objectForKey:recordKey]];
}]
continueWithSuccessBlock:^id(OSSTask *task) {
if (!task.result) {
// 如果本地尚无记录,调用初始化UploadId接口获取
OSSInitMultipartUploadRequest * initMultipart = [OSSInitMultipartUploadRequest new];
initMultipart.bucketName = bucketName;
initMultipart.objectKey = objectKey;
initMultipart.contentType = @"application/octet-stream";
return [client multipartUploadInit:initMultipart];
}
OSSLogVerbose(@"An resumable task for uploadid: %@", task.result);
return task;
}]
continueWithSuccessBlock:^id(OSSTask *task) {
NSString * uploadId = nil;
if (task.error) {
return task;
}
if ([task.result isKindOfClass:[OSSInitMultipartUploadResult class]]) {
uploadId = ((OSSInitMultipartUploadResult *)task.result).uploadId;
} else {
uploadId = task.result;
}
if (!uploadId) {
return [OSSTask taskWithError:[NSError errorWithDomain:OSSClientErrorDomain
code:OSSClientErrorCodeNilUploadid
userInfo:@{OSSErrorMessageTOKEN: @"Can't get an upload id"}]];
}
// 将“记录键:UploadId”持久化到本地存储
NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:uploadId forKey:recordKey];
[userDefault synchronize];
return [OSSTask taskWithResult:uploadId];
}]
continueWithSuccessBlock:^id(OSSTask *task) {
// 持有UploadId上传文件
OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
resumableUpload.bucketName = bucketName;
resumableUpload.objectKey = objectKey;
resumableUpload.uploadId = task.result;
resumableUpload.uploadingFileURL = filePath;
resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
float number = (float)totalBytesSent/(float)totalBytesExpectedToSend;
self.videoHud.progress = number;
};
return [client resumableUpload:resumableUpload];
}]
continueWithBlock:^id(OSSTask *task) {
if (task.error) {
if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
// 如果续传失败且无法恢复,需要删除本地记录的UploadId,然后重启任务
[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];
}
} else {
dispatch_async(dispatch_get_main_queue(), ^{
[self.videoHud hide:YES];
self.videoHud = nil;
//删除沙盒下面对应的视频文件
// NSFileManager *defauleManager = [NSFileManager defaultManager];
// NSString *tempPath = [filePath absoluteString];
// [defauleManager removeItemAtPath:tempPath error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileListArray = [fileManager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] error:nil];
for (NSString *file in fileListArray)
{
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] stringByAppendingPathComponent:file];
NSString *extension = [path pathExtension];
if ([extension compare:@"mp4" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
[fileManager removeItemAtPath:path error:nil];
}
}
});
NSLog(@"上传完成!");
// 上传成功,删除本地保存的UploadId
_uploadid = nil;
[[NSUserDefaults standardUserDefaults] removeObjectForKey:recordKey];
[self uploadVideoInfoWithObjectKey:objectKey duration:[NSString stringWithFormat:@"%f.1",VideoDuration]];
}
return nil;
}];
}
.....