AVAudioRecorder如何在iPhone中获得麦克风级别?

时间:2013-08-13 07:05:49

标签: iphone ios ios6

我正在开发iphone 6+的录音应用程序 问题1:(AVAudioRecorder)录音在模拟器中工作正常但在设备中无法正常工作..

音频设置:

[settings setValue:[NSNumber numberWithInteger:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];

[settings setValue:[NSNumber numberWithFloat:44100.0f] forKey:AVSampleRateKey];

[settings setValue:[NSNumber numberWithInteger:1] forKey:AVNumberOfChannelsKey];

[settings setValue:[NSNumber numberWithInteger:AVAudioQualityLow] forKey:AVEncoderAudioQualityKey];

问题2:在我的ipad中使用麦克风之前。但是当我使用这段代码时

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
 [audioSession setActive:YES error:&err];

mic无法在ipad中工作..如何在ipad / iphone中重置或获取麦克风级别

1 个答案:

答案 0 :(得分:1)

在我的- (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]);

} 

如果我有任何问题或方法可以改进我的答案,请告知我们。在这里还是很新的。