播放声音时录制音频

时间:2013-04-10 16:00:56

标签: iphone ios avaudioplayer avaudiorecorder

是否可以使用AVAudioRecorder录制音频并同时使用AVAudioPlayer播放另一个音频文件?

1 个答案:

答案 0 :(得分:0)

iOS 6可以实现。我自己在iOS 5.x中遇到了问题。没有关于5.x之前版本的信息。

为此,必须将AudioSession类别设置为AVAudioSessionCategoryPlayAndRecord

NSError *error = nil;
NSLog(@"Setting category for AudioSession to AVAudioSessionCategoryPlayAndRecord");
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
if (!success) {
    NSLog(@"Error setting category for AudioSession:\n\terror: %@", error.localizedDescription);
}

AVAudioRecorder的设置如下:

NSString *fileToRecordPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"record.m4a"];
NSURL *fileToRecordURL = [NSURL fileURLWithPath:fileToRecordPath];
NSDictionary *settings = @{AVFormatIDKey: [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
                           AVSampleRateKey: [NSNumber numberWithFloat:44100.0],
                           AVNumberOfChannelsKey: [NSNumber numberWithInt:1]};
NSError *error = nil;

AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc] initWithURL:self.fileURL settings:settings error:&error];
 if (!audioRecorder) {
    NSLog(@"Error initializing AVAudioRecorder:\n\terror: %@", error.localizedDescription);
}
audioRecorder.delegate = self;
[audioRecorder prepareToRecord];

在AVAudioPlayer中播放另一个音频文件(格式相同,m4a)时,一切都可以在iOS 6中正常工作。在iOS 5中,行为很奇怪。暂停播放音频或音频播放时,无法开始录制。当开始首先录制时,可以同时播放(另一个文件)。

经过一番搜索,我无法找到正确设置的方法。虽然我无法相信,但这是iOS中的一个错误,但缺少设置。

所以这适用于iOS 6,但对iOS 5问题的帮助非常受欢迎; o)