我创建的iOS应用程序具有录制音频几分钟的功能。我需要每10/20/30秒有一些自动保存功能,以便在应用程序崩溃/拨入电话/完全关闭应用程序时有一个后备。
我已经尝试过了:
如何制作某种自动保存功能,以便我始终对录制的音频文件进行回退?
我使用AVAudioRecorder
和AVAudioSession
录制音频。导出音频文件(完成时或崩溃/关闭时)是使用AVMutableComposition
和AVAssetExportSession
完成的。
以下是我的一些初始化AVAudioRecorder
:
self.recorder = [[AVAudioRecorder alloc] initWithURL:filePath settings:_recordSetting error:NULL];
self.recorder.delegate = self;
self.recorder.meteringEnabled = YES;
[self.recorder prepareToRecord];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
以下是我导出音频的方式:
AVMutableComposition* composition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *audioCombinedTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[audioCombinedTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [audio1 duration]) ofTrack:[audio1.tracks objectAtIndex:0] atTime:kCMTimeZero error:&error];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
NSString *latestFileName = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
NSString *exportPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.wav", latestFileName]];
_exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = _exportURL;
exportSession.outputFileType = AVFileTypeWAVE;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSLog (@"Exporting. status is %ld", (long)exportSession.status);
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
NSLog(@"export failed");
break;
case AVAssetExportSessionStatusExporting: {
NSLog(@"export exporting");
break;
}
case AVAssetExportSessionStatusCancelled: {
NSLog(@"export cancelled");
break;
}
case AVAssetExportSessionStatusWaiting: {
NSLog(@"export waiting");
break;
}
case AVAssetExportSessionStatusUnknown: {
NSLog(@"export unknown");
break;
}
case AVAssetExportSessionStatusCompleted: {
NSLog(@"export done");
break;
}
};
}];
注意:使用应用程序时(只需录制和停止录音机),音频文件会正确创建,一切正常。