我试图像这样获得麦克风音量: 在头文件中:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
@interface AlarmViewController : UIViewController {
AVAudioRecorder *recorder;
NSTimer *levelTimer;
}
@property (strong, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
@property (strong, nonatomic) IBOutlet UILabel *timeLabel;
- (void)timeChange:(NSTimer *)timer;
- (void)levelTimerCallback:(NSTimer *)timer;
@end
在实施文件中:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:44100.0], AVSampleRateKey, [NSNumber numberWithInt:kAudioFormatAppleLossless], AVFormatIDKey, [NSNumber numberWithInt:1], AVNumberOfChannelsKey, [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, nil];
NSError *error;
recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
if (recorder) {
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
[recorder record];
levelTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(levelTimerCallback:) userInfo:nil repeats:YES];
}
else {
NSLog(@"%@", [error description]);
}
}
- (void)levelTimerCallback:(NSTimer *)timer {
[recorder updateMeters];
NSLog(@"Average input: %f Peak input: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0]);
}
因此,在日志中它返回以下内容:
2014-06-29 16:31:42.400 NightLight[1140:388914] Average input: -120.000000 Peak input: -120.000000
我不知道该怎么办?我确信它可以在iPhone的隐私设置中使用麦克风。
答案 0 :(得分:1)
事实证明,您需要使用AVAudioSession为应用程序设置上下文。在 [super viewDidLoad];
之后的 - (void)viewDidLoad 中添加以下代码// Set audio context to app
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];