iOS之声音捕捉
现在需要在ios上实现这样一个功能:
监听外部的声音,当有声音且达到一定的分贝后,通知相关事件就可以了。
真机测试已经通过的代码:
主要的是一个类:
1 #import <UIKit/UIKit.h> 2 #import <AVFoundation/AVFoundation.h> 3 #import <CoreAudio/CoreAudioTypes.h> 4 5 @interface MicBlowViewController : UIViewController { 6 AVAudioRecorder *recorder; 7 NSTimer *levelTimer; 8 double lowPassResults; 9 } 10 - (void)start; 11 - (void)levelTimerCallback:(NSTimer *)timer; 12 13 @end
1 #import "MicBlowViewController.h" 2 #import "MicManager.h" 3 4 @implementation MicBlowViewController 5 6 - (void)start { 7 NSURL *url = [NSURL fileURLWithPath:@"/dev/null"]; 8 9 NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys: 10 [NSNumber numberWithFloat: 44100.0], AVSampleRateKey, 11 [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey, 12 [NSNumber numberWithInt: 1], AVNumberOfChannelsKey, 13 [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey, 14 nil]; 15 16 NSError *setCategoryError = nil; 17 18 [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryRecord error: &setCategoryError]; 19 20 NSError *error; 21 22 recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; 23 if (recorder) { 24 [recorder prepareToRecord]; 25 recorder.meteringEnabled = YES; 26 [recorder record]; 27 levelTimer = [NSTimer scheduledTimerWithTimeInterval: 0.03 target: self selector: @selector(levelTimerCallback:) userInfo: nil repeats: YES]; 28 } 29 } 30 31 32 - (void)levelTimerCallback:(NSTimer *)timer { 33 [recorder updateMeters]; 34 35 const double ALPHA = 0.05; 36 double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0])); 37 lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults; 38 39 if (lowPassResults < 0.25) 40 { 41 NSLog(@"\n 当前音量:%f \n",lowPassResults); 42 } 43 else 44 { 45 NSLog(@"\n 有声音啦: %f \n",lowPassResults); 46 [levelTimer invalidate]; 47 [recorder release]; 48 } 49 } 50 51 @end
代码有借鉴网络,加上自己的后期加工,成为了自己的项目。需要注意的是加上:
18行的代码。
否则会出现声音峰值的返回永远是-160。
然后就是开一个timer循环监听外部声音的情况,达到一定峰值,触发相关函数进行处理。