我正在使用AVFoundation使用图像和声音文件创建电影文件(mp4)。
我已经使用AVAssetWriterInputPixelBufferAdaptor成功创建了电影文件,该文件在电影文件中附加了CVPixelBufferRef(从UIImage对象中删除)。
现在,我想从该电影中的文件中添加音频内容。从设备麦克风中获取数据不是我在想的。并且,我找不到类似于AVAssetWriterInputPixelBufferAdaptor的任何内容,它可以帮助将音频数据写入该电影文件。
我在这里遗漏了什么吗?
答案 0 :(得分:5)
至少对我来说,解决方案是使用AVMutableComposition类。
1)创建AVMutableComposition类对象
2)创建2个AVURLAsset类对象,第一个基于您的视频文件,第二个基于您要从中提取音轨的文件
3)创建2个AVMutableCompositionTrack类对象,如前一个带音频轨道,第二个带视频轨道(基于2个适当的资产对象))
4)根据1)中的组合对象创建AVAssetExportSession类
5)导出你的会话
祝你好运
答案 1 :(得分:2)
感谢@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;
}