ios麦克风音量实时检测

热门标签

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

一、引入系统库

#import <AVFoundation/AVFoundation.h>

二、全局变量声明

@interface ViewController ()
{
    AVAudioRecorder *recorder;
    NSTimer *levelTimer;
}
@property(nonatomic,strong)UILabel *labelVoice;
@property(nonatomic,strong)CALayer *layerVoice;

@end

三、功能部分

1、UI部分

- (UILabel *)labelVoice
{
    if (!_labelVoice)
    {
        _labelVoice = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 120, 50)];
        _labelVoice.backgroundColor = [UIColor orangeColor];
        
        self.layerVoice = [CALayer layer];
        self.layerVoice.backgroundColor = [[UIColor greenColor]CGColor];
        self.layerVoice.frame = _labelVoice.bounds;
        [_labelVoice.layer addSublayer:_layerVoice];
    }
    return _labelVoice;
}

2、功能部分

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.labelVoice];
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionAllowBluetooth error:nil];
    
    /* 不需要保存录音文件 */
    NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
    
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 2], 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.3 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES];
    }
    else
    {
        NSLog(@"%@", [error description]);
    }
}

/* 该方法确实会随环境音量变化而变化,但具体分贝值是否准确暂时没有研究 */
- (void)levelTimerCallback:(NSTimer *)timer {
    [recorder updateMeters];
    
    float   level;                // The linear 0.0 .. 1.0 value we need.
    float   minDecibels = -60.0f; // use -80db Or use -60dB, which I measured in a silent room.
    float   decibels    = [recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels)
    {
        level = 0.0f;
    }
    else if (decibels >= 0.0f)
    {
        level = 1.0f;
    }
    else
    {
        float   root            = 5.0f; //modified level from 2.0 to 5.0 is neast to real test
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        float   amp             = powf(10.0f, 0.05f * decibels);
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    /* level 范围[0 ~ 1], 转为[0 ~120] 之间 */
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"voice updated :%f",level * 120);
        self.layerVoice.frame = CGRectMake(0, 0, level * 120, 50);
    });
}

 

标签:

未经允许不得转载:作者:SheaYang, 转载或复制请以 超链接形式 并注明出处 技术狗|博客
原文地址:《ios麦克风音量实时检测》 发布于2019-12-03

分享到:
赞(0)

评论 抢沙发

9 + 4 =


ios麦克风音量实时检测

长按图片转发给朋友

Vieu4.0主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录