美文网首页
iOS-SDAVAssetExportSession 的使用

iOS-SDAVAssetExportSession 的使用

作者: HanZhiZzzzz | 来源:发表于2022-10-19 12:43 被阅读0次
-(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 的使用

  • iconfont的使用(下载使用)

    1、下载文件 2、在生命周期中引入项目 beforeCreate () { var domModule = ...

  • Gson的使用--使用注解

    Gson为了简化序列化和反序列化的过程,提供了很多注解,这些注解大致分为三类,我们一一的介绍一下。 自定义字段的名...

  • 记录使用iframe的使用

    默认记录一下----可以说 这是我第一次使用iframe 之前都没有使用过; 使用方式: 自己开发就用了这几个属...

  • with的使用

    下面例子可以具体说明with如何工作: 运行代码,输出如下

  • this的使用

    什么是this? this是一个关键字,这个关键字总是返回一个对象;简单说,就是返回属性或方法“当前”所在的对象。...

  • this的使用

    JS中this调用有几种情况 一:纯粹的函数调用 这是函数的最通常用法,属于全局性调用,因此this就代表全局对象...

  • ==的使用

    积累日常遇到的编码规范,良好的编码习惯,持续更新。。。 日常使用==用于判断的时候,习惯性将比较值写前面,变量写后...

  • this的使用

    1.默认绑定,就是函数立即执行。 函数立即执行就是指向window,但是如果是node环境,就是指向全局conso...

  • %in% 的使用

    写在前面:From 生信技能书向量难点之一:%in% 难点 (1)== 与 %in% 的区别== 强调位置,x和对...

网友评论

      本文标题:iOS-SDAVAssetExportSession 的使用

      本文链接:https://www.haomeiwen.com/subject/ouruzrtx.html