码迷,mamicode.com
首页 > 移动开发 > 详细

ios 视频拼接/合成

时间:2016-06-13 18:57:16      阅读:1611      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

上面的图说明的是这个混合的过程,下面放代码:

- (void)mergeAndExportVideos:(NSArray*)videosPathArray withOutPath:(NSString*)outpath{
    if (videosPathArray.count == 0) {
        return;
    }
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    
    AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                    preferredTrackID:kCMPersistentTrackID_Invalid];
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                    preferredTrackID:kCMPersistentTrackID_Invalid];
    CMTime totalDuration = kCMTimeZero;
    for (int i = 0; i < videosPathArray.count; i++) {
        AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:videosPathArray[i]]];
        NSError *erroraudio = nil;
     //获取AVAsset中的音频 或者视频 AVAssetTrack
*assetAudioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
     //向通道内加入音频或者视频 BOOL ba
= [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:assetAudioTrack atTime:totalDuration error:&erroraudio]; NSLog(@"erroraudio:%@%d",erroraudio,ba); NSError *errorVideo = nil; AVAssetTrack *assetVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo]firstObject]; BOOL bl = [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:assetVideoTrack atTime:totalDuration error:&errorVideo]; NSLog(@"errorVideo:%@%d",errorVideo,bl); totalDuration = CMTimeAdd(totalDuration, asset.duration); } NSLog(@"%@",NSHomeDirectory()); NSURL *mergeFileURL = [NSURL fileURLWithPath:outpath]; AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPreset640x480]; exporter.outputURL = mergeFileURL; exporter.outputFileType = AVFileTypeMPEG4; exporter.shouldOptimizeForNetworkUse = YES; [exporter exportAsynchronouslyWithCompletionHandler:^{ NSLog(@"exporter%@",exporter.error); }];

下面是方法详解:

- (AVMutableCompositionTrack *)addMutableTrackWithMediaType:(NSString *)mediaType preferredTrackID:(CMPersistentTrackID)preferredTrackID;

参数:

mediaType          :数据类型  AVMediaTypeVideo 视频   AVMediaTypeAudio  音频

preferredTrackID :可自由设定 但建议kCMPersistentTrackID_Invalid也就是0

//向通道内加入音频或者视频
- (BOOL)insertTimeRange:(CMTimeRange)timeRange ofTrack:(AVAssetTrack *)track atTime:(CMTime)startTime error:(NSError * __nullable * __nullable)outError;

参数:

timeRange:  插入视频/音频的的时间段

track        :插入的视频/音频

ios 视频拼接/合成

标签:

原文地址:http://www.cnblogs.com/chaochaobuhuifei55/p/5581291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!