iOS每日一记之———————————————视频 拍摄 与压缩 阿里云OSS断点续传

.....

视频拍摄

//调用系统录像
- (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;
     }];
}

.....








  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现Vue阿里云OSS断点续传,可以按照以下步骤进行操作: 1. 首先,安装ali-oss依赖库,可以使用npm命令进行安装:npm install ali-oss --save。 2. 创建一个RAM用户,分配相应的角色和权限策略,确保该用户拥有上传文件到OSS的权限。 3. 在Vue项目中引入OSS对象,并声明一个全局变量ossClient和tempCheckpoint。可以在项目的入口文件或者所需要使用的组件中引入OSS对象。例如,使用require语句引入OSS对象:const OSS = require('ali-oss')。 4. 初始化ossClient和tempCheckpoint变量,ossClient用于连接到阿里云OSS服务,tempCheckpoint用于记录已完成上传的分片及其对应的etag值。 5. 在文件上传时,根据需要将文件切分成多个分片,并使用ossClient.uploadPart方法进行分片上传。在每次分片上传完成后,更新tempCheckpoint数组。 6. 如果上传过程中中断了,可以通过tempCheckpoint数组来恢复上次上传的进度。重新初始化ossClient,并使用ossClient.uploadPart方法继续上传剩余的分片。 通过以上步骤,就可以实现Vue阿里云OSS断点续传功能。这样即使在上传大文件的过程中出现中断,也可以从上次中断的地方继续上传,提高文件上传的可靠性和效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [阿里云oss文件分片、断点续传上传](https://blog.csdn.net/m0_49106791/article/details/119766365)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值