AVAudioRecorder / AVAudioPlayer – 追加logging到文件
有什么方法可以录制到audio文件的末尾? 我们不能只是暂停logging而不是停止logging,因为用户需要能够稍后回到应用程序,并添加更多的audio到他们的logging。 目前,audio以NSDataforms存储在CoreData中。 NSData的AppendData
不起作用,因为生成的audio文件仍然报告它只与原始数据一样长。
另一种可能性是将原始的audio文件和新的audio文件一起,并将它们连接成一个audio文件,如果有什么办法的话。
这可以使用AVMutableComposionTrack insertTimeRange:ofTrack:atTime:error
相当容易地完成。 代码有点冗长,但实际上就像4个步骤:
// Create a new audio track we can append to AVMutableComposition* composition = [AVMutableComposition composition]; AVMutableCompositionTrack* appendedAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; // Grab the two audio tracks that need to be appended AVURLAsset* originalAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:originalAudioPath] options:nil]; AVURLAsset* newAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:newAudioPath] options:nil]; NSError* error = nil; // Grab the first audio track and insert it into our appendedAudioTrack AVAssetTrack *originalTrack = [originalAsset tracksWithMediaType:AVMediaTypeAudio]; CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, originalAsset.duration); [appendedAudioTrack insertTimeRange:timeRange ofTrack:[originalTrack objectAtIndex:0] atTime:kCMTimeZero error:&error]; if (error) { // do something return; } // Grab the second audio track and insert it at the end of the first one AVAssetTrack *newTrack = [newAsset tracksWithMediaType:AVMediaTypeAudio]; timeRange = CMTimeRangeMake(kCMTimeZero, newAsset.duration); [appendedAudioTrack insertTimeRange:timeRange ofTrack:[newTrack objectAtIndex:0] atTime:originalAsset.duration error:&error]; if (error) { // do something return; } // Create a new audio file using the appendedAudioTrack AVAssetExportSession* exportSession = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetAppleM4A]; if (!exportSession) { // do something return; } NSString* appendedAudioPath= @""; // make sure to fill this value in exportSession.outputURL = [NSURL fileURLWithPath:appendedAudioPath]; exportSession.outputFileType = AVFileTypeAppleM4A; [exportSession exportAsynchronouslyWithCompletionHandler:^{ // exported successfully? switch (exportSession.status) { case AVAssetExportSessionStatusFailed: break; case AVAssetExportSessionStatusCompleted: // you should now have the appended audio file break; case AVAssetExportSessionStatusWaiting: break; default: break; } NSError* error = nil; }];
添加两个文件并使用exportAsynchronouslyWithCompletionHandler
方法导出组合后,可以通过创buildAVMutableCompositionTrack
追加两个audio文件。
请参阅下面的链接了解更多详情。
AVAssetExportSession类参考
创造新资产
希望这有助于解决您的问题。
我没有完整的代码示例,但扩展audio文件服务可以帮助您连接两个audio文件。 在Xcode中search扩展audio文件服务或访问下面的链接。
苹果文档