如何在iphone sdk中合并音频和视频

时间:2013-12-19 09:44:14

标签: ios iphone objective-c audio video

我正在创建一个项目,其中我使用目标c中的以下代码合并视频和音频。

AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSString *audio_inputFilePath = [libraryDirectory stringByAppendingPathComponent:@"SelectedSong.wav"];
NSURL    *audio_inputFileUrl = [NSURL fileURLWithPath:audio_inputFilePath];
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];

NSString *videoOutputPath = [libraryDirectory stringByAppendingPathComponent:@"Video.mp4"];
NSURL    *video_inputFileUrl = [NSURL fileURLWithPath:videoOutputPath];
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];

CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);

AVMutableCompositionTrack *a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

[a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];

AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

[b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];

AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
_assetExport.outputFileType = @"com.apple.quicktime-movie";
//_assetExport.outputFileType = AVFileTypeMPEG4 ;
//NSLog(@"support file types= %@", [_assetExport supportedFileTypes]);
_assetExport.outputURL = outputFileUrl;

[_assetExport exportAsynchronouslyWithCompletionHandler:^{
        };

 [[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]

它返回设备中的空数组。 当在模拟器中检查它时它工作正常。


所以请帮助我如何解决它。

1 个答案:

答案 0 :(得分:0)

在那种情况下

[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]

[b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];这不能读取数组。

因为声音/音频不存在于特定文件中。此错误仅在这些情况下出现,当声音/音频不存在于特定多媒体文件中时。