在我的- (void)setUpAudio
方法中,我创建了一个字典,其中包含 AVAudioRecorder 的设置。(它有点干净)您上面的代码几乎是正确的,但并不完全正确。见下文。
// empty URL
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
// define settings for AVAudioRecorder
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
[NSNumber numberWithInt:1], AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey,
nil];
NSError *error;
// init and apply settings
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
// This here is what you are missing, without it the mic input will work in the simulator,
// but not on a device.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
NSTimer *levelTimer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(levelTimerCallback:) userInfo:nil repeats:YES];
[recorder record];
} else {
NSLog([error description]);
}
然后在更新方法中,您可以像这样跟踪您的麦克风输入电平。
- (void)levelTimerCallback:(NSTimer *)timer {
[recorder updateMeters];
NSLog(@"Average input: %f Peak input: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0]);
}
任何问题或我可以改进答案的方法,请告诉我。这里还是很新的。