iOS:合并两个视频,其中一个视频不显示但声音正在播放

时间:2015-02-01 13:18:41

标签: ios objective-c video

我试图合并2个视频,一个是我从youtube下载的,另一个是我用UIImagePickerController拍摄的。 合并后,youtube的视频无法显示,但声音正在播放。 我猜这个问题是由视频尺寸之间的差异造成的。

这是我的代码,我做错了什么?

- (void) MergeVideos {
NSLog(@"start merge");
NSError *avError = nil;
//NSFileManager *fileManager = [NSFileManager defaultManager];

AVMutableComposition *composition = [AVMutableComposition composition];

for (int i = ((int)[videos_arr2 count]-1); i>= 0; i--) {
    AVURLAsset *tmpAsset = [[AVURLAsset alloc] initWithURL:videos_arr2[i] options:nil];

[composition insertTimeRange:CMTimeRangeMake(kCMTimeZero, tmpAsset.duration) ofAsset:tmpAsset atTime:kCMTimeZero error:&avError];
}

AVAssetExportSession *export = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];

export.outputFileType = AVFileTypeMPEG4;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSFileManager *manager = [NSFileManager defaultManager];

NSString *outputURL = [documentsDirectory stringByAppendingPathComponent:@"movie"] ;
[manager createDirectoryAtPath:outputURL withIntermediateDirectories:YES attributes:nil error:nil];

outputURL = [outputURL stringByAppendingPathComponent:@"movie.mp4"];
[manager removeItemAtPath:outputURL error:nil];

export.outputURL = [NSURL fileURLWithPath:outputURL];

[export exportAsynchronouslyWithCompletionHandler:^(void) {
    player = [[MPMoviePlayerController alloc] initWithContentURL:export.outputURL];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinishedCallback:)                                                                name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    player.movieSourceType = MPMovieSourceTypeFile;
    [player prepareToPlay];
    player.controlStyle = MPMovieControlStyleNone;
    [player setShouldAutoplay:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayerLoadStateChanged:)
                                                 name:MPMoviePlayerLoadStateDidChangeNotification
                                               object:player];
}];

}

1 个答案:

答案 0 :(得分:0)

看起来您正在kCMTimeZero中插入两个AVAssets。您应该在上一个资产的持续时间中插入下一个资产:

CMTime nextAddTime = kCMTimeZero;
for (int i = ((int)[videos_arr2 count]-1); i>= 0; i--) {
    AVURLAsset *tmpAsset = [[AVURLAsset alloc] initWithURL:videos_arr2[i] options:nil];

[composition insertTimeRange:CMTimeRangeMake(kCMTimeZero, tmpAsset.duration) ofAsset:tmpAsset atTime:nextAddTime error:&avError];
nextAddTime = CMTimeAdd(nextAddTime, tmpAsset.duration);
}