ビデオとバックグラウンドオーディオを組み合わせようとしています。1つのビデオと1つのオーディオファイル(SOでありがたいことに見つけました)でビデオを作成できましたが、2つ以上のオーディオファイルを使用するように拡張するのに問題があります。バックグラウンドオーディオは複数のファイルから取得できるので、それらを順番にビデオに追加したいと思います。
元。audio-1.cafの長さは2秒、audio-2.cafの長さは2秒、video-1.movの長さは4秒です。
audio-1を0〜2秒の時間間隔にし、audio-2を2〜4秒の時間間隔にします。残念ながら、私が作成したコードは、最初のオーディオ1で2秒のムービーを作成し、残りのムービーとオーディオは含まれていません。
ここで助けを求めることができるように、問題を単純化しました。以下のコードは、2つのオーディオソースを使用して空白のビデオを作成しようとします。(私の以前の実装は動的で、すべてのオーディオソースをループしていました)
-(void)writeAudio
{
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSDictionary * assetOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
NSString * outputFilePath = NSHomeDirectory();
outputFilePath = [outputFilePath stringByAppendingPathComponent:@"Library"];
outputFilePath = [outputFilePath stringByAppendingPathComponent:@"temp.mov"];
NSURL * outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
[[NSFileManager defaultManager] removeItemAtURL:outputFileUrl error:nil];
CMTime nextClipStartTime = kCMTimeZero;
NSURL * audioURL /* = kSomeValidURL */;
NSURL * audio2URL /* = kSomeOtherValidURL */;
AVURLAsset* audioAsset = [[AVURLAsset alloc] initWithURL:audioURL options:assetOptions];
CMTimeRange audio_timeRange = CMTimeRangeMake(nextClipStartTime, audioAsset.duration);
AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
nextClipStartTime = CMTimeAdd(nextClipStartTime, audio_timeRange.duration);
AVURLAsset* audio2Asset = [[AVURLAsset alloc] initWithURL:audio2URL options:assetOptions];
CMTimeRange audio2_timeRange = CMTimeRangeMake(nextClipStartTime, audio2Asset.duration);
AVMutableCompositionTrack *b_compositionAudio2Track = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[b_compositionAudio2Track insertTimeRange:audio2_timeRange ofTrack:[[audio2Asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
nextClipStartTime = CMTimeAdd(nextClipStartTime, audio2_timeRange.duration);
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
_assetExport.outputFileType = @"com.apple.quicktime-movie";
_assetExport.outputURL = outputFileUrl;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void ) {
NSLog(@"audio was completed???");
}
];
}
問題は同じままです。新しいビデオは最初のaudioURLのコンテンツで構成され、最初のaudioURLのコンテンツの長さです。