术语类
AVAsset:素材库里的素材;
AVAssetTrack:素材的轨道;
AVMutableComposition :一个用来合成视频的工程文件;
AVMutableCompositionTrack :工程文件中的轨道,有音频轨、视频轨等,里面可以插入各种对应的素材;
AVMutableVideoCompositionLayerInstruction:视频轨道中的一个视频,可以缩放、旋转等;
AVMutableVideoCompositionInstruction:一个视频轨道,包含了这个轨道上的所有视频素材;
AVMutableVideoComposition:管理所有视频轨道,可以决定最终视频的尺寸,裁剪需要在这里进行;
AVAssetExportSession:配置渲染参数并渲染。
接下来就用这种类比的方式裁剪一个视频:
1.将素材拖入到素材库中
AVAsset *asset = [AVAsset assetWithURL:outputFileURL];
//素材的视频轨
AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]objectAtIndex:0];
//素材的音频轨
AVAssetTrack *audioAssertTrack = [[asset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
2.将素材的视频插入视频轨,音频插入音频轨
//这是工程文件
AVMutableComposition *composition = [AVMutableComposition composition];
//视频轨道
AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//在视频轨道插入一个时间段的视频
[videoCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration) ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];
//音频轨道
AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
//插入音频数据,否则没有声音
[audioCompositionTrack insertTimeRange: CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration) ofTrack:audioAssertTrack atTime:kCMTimeZero error:nil];
3.裁剪视频,就是要将所有视频轨进行裁剪,就需要得到所有的视频轨,而得到一个视频轨就需要得到它上面所有的视频素材
AVMutableVideoCompositionLayerInstruction *videoCompositionLayerIns = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoAssetTrack];[videoCompositionLayerIns setTransform:videoAssetTrack.preferredTransform atTime:kCMTimeZero];
//得到视频素材(这个例子中只有一个视频)
AVMutableVideoCompositionInstruction *videoCompositionIns = [AVMutableVideoCompositionInstruction videoCompositionInstruction];[videoCompositionIns setTimeRange:CMTimeRangeMake(kCMTimeZero, videoAssetTrack.timeRange.duration)];
//得到视频轨道(这个例子中只有一个轨道)
AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];videoComposition.instructions = @[videoCompositionIns];videoComposition.renderSize = CGSizeMake(...);
//裁剪出对应的大小
videoComposition.frameDuration = CMTimeMake(1, 30);
4.导出
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];
exporter.videoComposition = videoComposition;exporter.outputURL = [NSURL fileURLWithPath:_outputFilePath isDirectory:YES];
exporter.outputFileType = AVFileTypeMPEG4;
exporter.shouldOptimizeForNetworkUse = YES;
[exporter exportAsynchronouslyWithCompletionHandler:^{
if (exporter.error) {
//...
}else{
//...
}
}];
网友评论