謝謝@peter。這是代碼解決方案。
-(BOOL)compositeVideo{
//Record cur video
NSURL *curAudio = [[NSBundle mainBundle]URLForResource:@"a" withExtension:@".pcm"];
NSURL *curVideo = [[NSBundle mainBundle]URLForResource:@"v" withExtension:@".mp4"];
AVAsset *video = [AVAsset assetWithURL:curVideo];
AVAsset *audio = [AVAsset assetWithURL:curAudio];
AVAssetTrack *vTrack = [[video tracksWithMediaType:AVMediaTypeVideo] firstObject];
NSArray *arr = [audio tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack *aTrack = [arr firstObject];
AVMutableComposition *composition = [AVMutableComposition composition];
AVMutableCompositionTrack *visualTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:1];
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
NSError *error;
[visualTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, video.duration) ofTrack:vTrack atTime:kCMTimeZero error:&error];
if (error) {
NSLog(@"video composition failed! error:%@", error);
return NO;
}
[audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audio.duration) ofTrack:aTrack atTime:kCMTimeZero error:&error];
if (error) {
NSLog(@"audio composition failed! error:%@", error);
return NO;
}
AVAssetExportSession *exporter = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
exporter.outputURL = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:@"compositedVideo.mp4"]];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
exporter.outputFileType = AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^{
if (exporter.error) {
NSLog(@"exporter synthesization failed! error:%@", error);
[self.delegate compositeDidFinishAtURL:nil duration:-1];
}else{
[self.delegate compositeDidFinishAtURL:exporter.outputURL duration:CMTimeGetSeconds(video.duration)];
}
}];
return YES;
}
我有非常類似的問題。在我的應用程序中,我創建了一個基於存儲在相機膠捲目錄中的視頻文件的電影(使用直接像素訪問進行了一些更改)。爲此,我使用了AVAsset/AVAssetReader/AVAssetWriter類和相關的。 我現在唯一的問題是我的電影不包含任何音軌,只是視頻數據。我想將音軌追加到來自原始視頻文件的電影中。出於某種原因,我無法在視頻正在寫入時這樣做,所以現在我正在尋找一種在視頻轉換完成後執行此操作的方法。 – peter 2011-02-27 15:59:28