1. 资源获取
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
在这个方法中info获取中获取视频URL。
不允许编辑的情况:使用UIImagePickerControllerReferenceURL
允许编辑的情况:获取UIImagePickerControllerMediaURL,这是编辑过的视频数据,存放于tmp目录中,可直接通过[[NSData alloc] initWithContentsOfURL:url];
获取数据,数据量大的情况,不应该读到内存中。在某些情况下,编辑失败UIImagePickerControllerMediaURL为空。依然通过UIImagePickerControllerReferenceURL获取。
2. 导出视频原始数据
即通过PHAsset方式导出。
PHFetchResult * fetchResult = [PHAsset fetchAssetsWithALAssetURLs: @[url] options: nil];
PHAsset * phasset = fetchResult.firstObject;
[[PHImageManager defaultManager] requestAVAssetForVideo:phasset options:nil resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
if (asset) {
AVURLAsset *a = (AVURLAsset *)asset;
NSData *data = [NSData dataWithContentsOfURL:a.URL];
NSLog(@"%ul",data.length);
}
}];
上述方法为异步导出。如果需要为同步:
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
PHVideoRequestOptions *option = [PHVideoRequestOptions new];
__block AVAsset *resultAsset;
[[PHImageManager defaultManager] requestAVAssetForVideo:videoAsset options:option resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
resultAsset = avasset;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
3. 自定义导出
- (void)CropVideo:(NSURL *)videoFileUrl withStartTime:(CGFloat)startTime stopTime:(CGFloat)stopTime outPutUrl:(NSURL *)ouputUrl finishBlock:(void(^)(BOOL))block{
AVAsset *anAsset = [[AVURLAsset alloc] initWithURL:videoFileUrl options:nil];
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:anAsset];
NSString *present;
if ([compatiblePresets containsObject:AVAssetExportPreset640x480]) {
present = AVAssetExportPreset640x480;
}else{
//get medium preset
present = compatiblePresets[compatiblePresets.count/2];
}
NSLog(@"preset %@",present);
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:anAsset presetName:present];
CMTime start = CMTimeMakeWithSeconds(startTime, anAsset.duration.timescale);
CMTime duration = CMTimeMakeWithSeconds(stopTime-startTime, anAsset.duration.timescale);
CMTimeRange range = CMTimeRangeMake(start, duration);
exportSession.timeRange = range;
exportSession.shouldOptimizeForNetworkUse = YES;
exportSession.fileLengthLimit = range.duration.value/range.duration.timescale*1024*80;
exportSession.outputURL = ouputUrl;
[[NSFileManager defaultManager] removeItemAtURL:ouputUrl error:nil];
exportSession.outputFileType = AVFileTypeMPEG4;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
BOOL flag = NO;
switch ([exportSession status]) {
case AVAssetExportSessionStatusFailed:
case AVAssetExportSessionStatusCancelled:
flag = NO;
break;
default:
flag = YES;
break;
}
if (block) {
block(flag);
}
if (flag) {
NSLog(@"export success to url:%@",ouputUrl);
}else{
NSLog(@"export failed");
}
}];
}