iOS:将空/黑帧添加到AVMutableComposition

时间:2013-02-04 23:46:47

标签: iphone ios avfoundation avmutablecomposition

从CAF录音开始,我需要创建一个视频文件,其中视频轨道只是空帧,音频轨道是这个录音文件。我知道这是一个奇怪的用例,这可能就是为什么我找不到有关如何操作的信息。我正在尝试使用AVMutableComposition,但我无法弄清楚如何让它发挥作用。

这就是我现在所拥有的:

AVMutableComposition *composition = [AVMutableComposition composition];    

/* soundFilePath is the path to the CAF audio file */
AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:soundFilePath] options:nil];
CMTimeRange fullTime = CMTimeRangeMake(kCMTimeZero, [audioAsset duration]);
AVAssetTrack *sourceAudioTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];

/* Add audio track */
AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionAudioTrack insertTimeRange:fullTime ofTrack:sourceAudioTrack atTime:kCMTimeZero error:nil];

/* docsDir is defined previously as the path to where I want to save the file */
NSString *videoFilePath = [docsDir stringByAppendingPathComponent:@"video.mov"];
NSURL *videoFileURL = [NSURL fileURLWithPath:videoFilePath];

AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];

exporter.outputFileType = AVFileTypeQuickTimeMovie;
exporter.outputURL = videoFileURL;

[exporter exportAsynchronouslyWithCompletionHandler:nil];

这让我得到的是一个包含音频的.mov文件,但没有视频。我需要该文件有某种视频内容 - 只是空视频帧。我对所有这些iOS库都很陌生,所以上面的所有代码基本上都是从各种示例中拼凑而成的,我当然还没有完全理解这一切是如何工作的。

如果这是正确的方法,我还尝试向AVMutableVideoComposition添加AVMutableComposition。为了做到这一点,我添加了一个空白视频轨道到AVMutableComposition,就像我添加音频轨道一样:

/* Add video track */
AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionVideoTrack insertEmptyTimeRange:fullTime];

然后我创建并配置了AVMutableVideoComposition,如下所示:

AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
videoComposition.frameDuration = [audioAsset duration];
videoComposition.renderScale = 1.0;
videoComposition.renderSize = CGSizeMake(320, 240);
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:compositionVideoTrack];
instruction.layerInstructions = [NSArray arrayWithObject:layerInstruction];
instruction.timeRange = compositionVideoTrack.timeRange;

videoComposition.instructions = [NSArray arrayWithObject:instruction];

最后,将AVMutableVideoComposition添加到AVMutableComposition

exporter.videoComposition = videoComposition;

然而,通过这种方法,我什么都没得到。没有创建视频文件。我在导出的完成处理程序中放了一个日志语句,它确实完成了,但没有创建视频文件。

对此的任何帮助将不胜感激。谢谢!

0 个答案:

没有答案