我在使用 AVAudioRecorder 时面临一个奇怪的问题。在我的应用程序中,我需要录制音频并播放它。我正在创建我的播放器:
if(recorder)
{
if(recorder.recording)
[recorder stop];
[recorder release];
recorder = nil;
}
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/%@.caf",songTitle]];
NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleIMA4],AVFormatIDKey,
[NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
[NSNumber numberWithInt: AVAudioQualityMax],AVEncoderAudioQualityKey,nil];
recorder = [[AVAudioRecorder alloc] initWithURL: [NSURL fileURLWithPath:filePath] settings: recordSettings error: nil];
recorder.delegate = self;
if ([recorder prepareToRecord] == YES){
[recorder record];
每次按下录制按钮时,我都会释放并创建播放器。但问题是,AVAudiorecorder 在开始录制之前需要一些时间,所以如果我连续多次按下录制按钮,我的应用程序会冻结一段时间。
当耳机连接到设备时,相同的代码可以正常工作,没有任何问题...录音没有延迟,即使我多次按下录音按钮,应用程序也不会冻结。
找到解决方案了。我刚刚添加了代码
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
err = nil;
[audioSession setActive:YES error:&err];
if(err){
NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
return;
}
现在工作正常。但是我想知道这段代码有什么区别?为什么我的应用程序在连接耳机时运行良好,但在没有耳机时就冻结了。?
是的,
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
就是解决方案。它可以让您录制和播放音频。
关于耳机错误,可能与属性有关
[[AVAudioSession sharedInstance] inputIsAvailable]