Article From:https://segmentfault.com/q/1010000011710622
Question:

Recently, the company added a feature to import videos from albums to compress and transcode album videos into MP4 format for uploading, but it always prompts for upload failure.
The code to get the video selected from the album is as follows

 - (IBAction)getVideos:(id)sender {
    ZZPhotoController* photoController = [[ZZPhotoController alloc] init];
    photoController.isVideo = YES;
    photoController.selectPhotoOfMax = 1;
    //Set the color of the dot dot next to the completion button in the album.PhotoController.roundColor = [UIColor greenColor];WS (weakSelf)[photOController showIn:self result:^ (ID responseObject){NSArray* array = (NSArray *) respOnseObject;PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];Options.version = PHVideoRequestOptionsVersionOriginal;Options.deliveryMode = PHVideoRequEstOptionsDeliveryModeHighQualityFormat;PHAsset *phasset = [array firstObject];If (phasset.mediaType = PHAssetResourceTypeVideo) {[SVProgressHUD showInfoWithStatus@ @ please upload a video].}else if (phasset.duration > 20) {[SVProgressHUD showInfoWithSTatus:@ "video time should not exceed 20s"];}else if (phasset.duration < 3) {[SVProgressHUD shoWInfoWithStatus:@ "video time can not be less than 3S"];}else {[[PHImageManager defaultManager] requeStAVAssetForVideo:phasset options:options resultHandler:^ (AVAsset * _Nullable asset, AVAudioMix * _NUllable audioMix, NSDictionary * _Nullable info) {AVURLAsset * urlAsset = (AVURLASSET *) asset;NSURL *string = urlAsset.URL;NSData *data = [NSDatA dataWithContentsOfURL:string];If (data.length > 10*1024*1024) {Dispatch_sync (dispatch_get_main_queue ()),[SVProgressHUD showInfoWIthStatus:@ "video size should not exceed 10M"];});}else{[Self.videoRecorder compressVideoUrl:urlAsset.URL];}]];}} failure:nil];}

Before the project has the function of recording video, after the video is compressed, transcoding code is as follows

 #pragma mark - compress compress- (void) compressVideoUrl: (NSURL *) url{AVAsset *asset = [AVAsset assetWithURL:url];If(asset.duration.value / asset.duration.timescale < MIN_TIME) {If ([_delegate respondsToS)Elector:@selector (recordDidTimeShort)] {[_delegate recordDidTimeShort];}/ / delete filesNSFileManager *fileManager = [NSFileManager defaultManager];[fileManageR removeItemAtURL:url error:nil];Return;}/ / display Chrysanthemum[ZZPhotoHud setTitle:@ "video processing"... "];[ZZPhotoHud showActiveHud];AVAssetTrack *assetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];CGFloat minValue = MIN (assetTrack.naturalSize.width, assetTrack.)NaturalSize.height);CGSize renderSize = CGSizeMake (minValue, minValue * 3 / 4);AVMutabLeComposition *mixComposition = [[AVMutableComposition alloc] init];NSError *audioError;NSError *videoError;AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrAckWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];[audioTrack inSertTimeRange:CMTimeRangeMake (kCMTimeZero, asset.duration)OfTrack:[[asset tRacksWithMediaType:AVMediaTypeAudio] firstObject]AtTime:kCMTimeZeroError:& audioError];AVMutableCompositionTrack *videoTrack = [mixCompositIon addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];[videoTrack insertTimeRange:CMTimeRangeMake (kCMTimeZero, asset.duration)OFTrack:assetTrackAtTime:kCMTimeZeroError:& VIdeoError];AVMutableVideoCompositionLayerInstruction *layerInst = [AVMutableVideoCompositionLAyerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];CGFloat rate = 1;CGAffineTransform layerTransform = CGAffineTransformMake (assetTrack.preferredTransform.a, ASSE)TTrack.preferredTransform.b, assetTrack.preferredTransform.c, assetTrack.preferredTransform.d, assetTrack.preferredTransform.tx * rate, assetTrack.preferredTransform.ty);LayerTransform = CGAffinETransformConcat (layerTransform, CGAffineTransformMake (1, 0, 0, 1, 0, - - assetTrack.naturalSize.width)(assetTrack.naturalSize.height) / 2); / / move upward to take the central influence.LayerTransform = CGAffineTransformScale (LA)YerTransform, rate, rate); / / shrink, the size of the video before and after solving is asymmetric.[layerInst setTransform:layerTransform atTime:kCMTimeZero];[layerInst setOpacity:0.0 atTime:asset.duration];AVMutableVideoCompositionInsTruction *mainInst = [AVMutableVideoCompositionInstruction videoCompositionInstruction];MainInsT.layerInstructions = @[layerInst];MainInst.timeRange = CMTimeRangeMake (kCMTimeZero, asset.dura)Tion);AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoCompositioN];VideoComposition.instructions = @[mainInst];VideoComposition.renderSize = renderSize;VideoComposition.frameDuration = CMTimeMake (1, 30);/ / system/ / AVAssetExportSession *exporTSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];/ / exportSession.videoComposition = videoComposition;/ / exportSession.outputFileType = AVFileTypeMPEG4;/ / NSURL *outFileUrl = [NSURL fileURLWithPath:[NSString stringWithForMat:@ "% @", "[url.relativePath stringByReplacingOccurrencesOfString:@" mov "withString:@" MP4]];/ / /ExportSession.outputURL = outFileUrl;/ / [exportSession exportAsynchronouslyWithCompletionHandler:/ / // / if (exportSession.status = = AVAssetExportSessionStatusCompleted) {/ / /NSLog (@ "compression success ~ ~");/ / NSFileManager *fileManager = [NSFileManager defaultManager];// [fileManager removeItemAtURL:url error:nil];/ / // / if ([_delegat)E respondsToSelector:@selector (recordDidFinishOutFileAtUrl:)] {/ / [_delegate recordDidFinishOutFileAtUrl:exportSession.outputURL];/ /}/ / // /}/ / else{/ / /NSLog (@ compression failure% @, exportSession.error);/ /}/ / // /];/ / third partySDAVAssetExportSession *session = [SDAVAssetExportSession exportSessionWithAsset:mixComposition];SeSsion.videoComposition = videoComposition;Session.outputFileType = AVFileTypeMPEG4;Session.outputURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@ "% @", [url.relativePath stringByReplaCingOccurrencesOfString:@ "mov" withString:@ "MP4"]];/ / session.delegate = self;Session.videoSettings =]AVVideoCodecKey:AVVideoCodecH264,AVVideoWidthKey:@1000, //[NSNumber numberWithInteger:CGRectGetWidth (_bgView.frame)],AVVideoHeightKey:@750, //[NSNumber numberWithInteger:CGRectGetHeight (_bgV)Iew.frame]],AVVideoCompressionPropertiesKey:@{AVVideoAverageBitRateKey:@1000000,AVVideoProfIleLevelKey:AVVideoProfileLevelH264High41}};Session.audioSettings =]AVFormatIDKey:@ (kAudioF)OrmatMPEG4AAC)AVNumberOfChannelsKey:@2,AVSampleRateKey:@16000,AVEncoderBitRateKey:@64000,};[session exportAsynchronouslyWithCompletionHandler:^{If (AVAssetExpo)RtSessionStatusCompleted = = session.status) {NSLog (@ "compression success ~ ~");Dispatch_asYNC (dispatch_get_main_queue ()),If ([_delegate respondsToSelector:@selector (recor)DDidFinishOutFileAtUrl:]] {[_delegate recordDidFinishOutFileAtUrl:session.outpUtURL];}/ / delete filesNSFileManager *fileManager = [NSFilEManager defaultManager];[fileManager removeItemAtURL:url error:nil];});}Else{NSLog (@ compression failure% @, session.error);}]];}

I also called this method, passing in the URL of the video retrieved from the album, but the callback method always showed that the compression failed, asking God for help.

Answer 0:

Do you post the output of session.error?

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *