iOS-SDAVAssetExportSession 的使用

-(void)actionWithAsset:(PHAsset *)asset coverImage:(UIImage *)coverImage{
    WS(weakSelf);
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionOriginal;
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
//         NSURL *outputUrl = [NSURL fileURLWithPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",movName]]];   //输出路径
                //保存至沙盒路径
                NSString *FileName = [NSString stringWithFormat:@"%@.mp4",[DataFoundation ret32bitString]];
                NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                NSString *videoPath = [NSString stringWithFormat:@"%@", pathDocuments];
                NSString *FileLocalUrl = [videoPath stringByAppendingPathComponent:FileName];
                NSURL *outputUrl = [NSURL fileURLWithPath:FileLocalUrl];
        
                 SDAVAssetExportSession *encoder =    [SDAVAssetExportSession.alloc initWithAsset:asset];
                  encoder.outputFileType = AVFileTypeMPEG4;
                  encoder.outputURL = outputUrl;
                  //视频设置
                  encoder.videoSettings = @
                  {
                  AVVideoCodecKey: AVVideoCodecH264,
                  AVVideoWidthKey: @(coverImage.size.width),
                  AVVideoHeightKey: @(coverImage.size.height),
                  AVVideoCompressionPropertiesKey: @
                      {
                      AVVideoAverageBitRateKey: @6000000,
                      AVVideoProfileLevelKey: AVVideoProfileLevelH264High40,
                      },
                  };
                  //音频设置
                  encoder.audioSettings = @
                  {
                  AVFormatIDKey: @(kAudioFormatMPEG4AAC),
                  AVNumberOfChannelsKey: @2,
                  AVSampleRateKey: @44100,
                  AVEncoderBitRateKey: @128000,
                  };
                    __weak typeof(self) weakSelf  = self;
                  [encoder exportAsynchronouslyWithCompletionHandler:^
                   {
                       if (encoder.status == AVAssetExportSessionStatusCompleted)
                       {
//                           NSData *outputData = [NSData dataWithContentsOfURL:encoder.outputURL]; //压缩后的视频
//                           [weakSelf saveAtta:outputData withName:movName toPath:USER_Chat_Folder_Path];//保存
                           CGFloat MaxVideoLength = ([weakSelf.ugcRecordDic getFloatValueForKey:@"MaxVideoLength" defaultValue:0.0] / 1024.00);// 视频最大大小
                           long fileSize = fileSizeAtPath(FileLocalUrl);
                           if (fileSize / 1024.00 / 1024.00 > MaxVideoLength) {
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   [MBProgressHUD hideHUDForView:weakSelf.view];
                                   MakeOneCacleBtnAlert([[UIApplication sharedApplication].delegate window].rootViewController, @"提醒", [NSString stringWithFormat:@"添加失败,视频压缩后需限制在%@M以内!",formatFloat(MaxVideoLength)], @"确定");
                                   weakSelf.navigationItem.rightBarButtonItem.enabled  = YES;
                               });
                               return ;
                           }
                           NSError *error = nil;
                           NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:FileLocalUrl error:&error];
                           NSString *time;
                           if (fileAttributes) {
                               if (fileAttributes != nil) {
                                   NSDate *fileModDate;
                                   //文件修改日期
                                   if ((fileModDate = [fileAttributes objectForKey:NSFileModificationDate])) {
                                       NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                                       [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SSS"];
                                       [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
                                       [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

                                       NSString *currentDateString = [dateFormatter stringFromDate:fileModDate];
                                       if (currentDateString != nil && currentDateString.length >= 20) {
                                           time = [DateFoundation formateDate:[currentDateString  substringToIndex:20] withFormate:@"yyyy-MM-dd HH:mm:ss"];
                                           //NSLog(@"Modification date: %@\n  currentDateString -- %@ \n    time -- %@\n ", fileModDate,currentDateString,time);
                                       }
                                   }
                               }
                           }
       //                    dispatch_async(dispatch_get_main_queue(), ^{
       //                        [MBProgressHUD hideHUDForView:weakSelf.view];
       //                    });
                           NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"name":FileName?FileName:@"",
                                                                                                      @"path":FileLocalUrl?FileLocalUrl:@"",
                                                                                                      @"size":sizeOfFile(fileSize),
                                                                                                      @"time":time?time:@"",
                                                                                                      @"type":@"1"
                                                                                                      }];

                           LocalVedioModel *localVedioModel  = [LocalVedioModel mj_objectWithKeyValues:dic];
                           localVedioModel.coverImage = coverImage;
                           [weakSelf localVedioMLinkChangeResult:localVedioModel];
       //                    dispatch_async(dispatch_get_main_queue(), ^{
       //                        [weakSelf noStudent];
       //                        [weakSelf.tableV reloadData];
                           //                    });
       //                    //                NSData *data = [NSData dataWithContentsOfFile:model.FileLocalUrl];
       //                    //model.fileData = data;
                         
                       }
                       else if (encoder.status == AVAssetExportSessionStatusCancelled)
                       {
                           NSLog(@"Video export cancelled");
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [MBProgressHUD hideHUDForView:weakSelf.view];
                               [MBProgressHUD showMoreLine:@"添加取消" view:nil];
                               weakSelf.navigationItem.rightBarButtonItem.enabled  = YES;
                           });
                       }
                       else
                       {
                           NSLog(@"Video export failed with error: %@ (%ld)", encoder.error.localizedDescription, (long)encoder.error.code);
                           // log error to text view
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [MBProgressHUD hideHUDForView:weakSelf.view];
                               [MBProgressHUD showMoreLine:@"添加失败" view:nil];
                               weakSelf.navigationItem.rightBarButtonItem.enabled  = YES;
                           });
                       }
                   }];
    }];
}

你可能感兴趣的:(iOS-SDAVAssetExportSession 的使用)