IOS15音频录音
#import "ViewController.h"
#import <AVKit/AVKit.h>
@interface ViewController ()
@property(nonatomic,strong)AVAudioRecorder *recoder;
@property(nonatomic,strong)CADisplayLink *displayLink;
//静音的持续时间
@property(nonatomic,assign)CGFloat slientDuration;
@end
@implementation ViewController
- (IBAction)startRecoord:(id)sender {
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [doc stringByAppendingPathComponent:@"test3.caf"];
NSURL *ulr1 = [NSURL fileURLWithPath:path];
NSLog(@"%@",ulr1);
// setting:录音的设置项
NSDictionary *configDic = @{// 编码格式
AVFormatIDKey:@(kAudioFormatLinearPCM),
// 采样率
AVSampleRateKey:@(11025.0),
// 通道数
AVNumberOfChannelsKey:@(2),
// 录音质量
AVEncoderAudioQualityKey:@(AVAudioQualityMin)
};
self.recoder = [[AVAudioRecorder alloc]initWithURL:ulr1 settings:configDic error:nil];
//开启分贝测量功能
self.recoder.meteringEnabled = YES;
[self.recoder prepareToRecord];
[self.recoder record];
[self addTime];
// [self.recoder averagePowerForChannel:0];
}
- (IBAction)stopRecoard:(id)sender {
[self.recoder stop];
[self removeTime];
}
-(void)update1{
// NSLog(@"%f",[self.recoder averagePowerForChannel:0]);
//更新测量值
[self.recoder updateMeters];
float power = [self.recoder averagePowerForChannel:0];
if(power <= -20){ //几乎为静音
self.slientDuration += self.displayLink.duration;
if(self.slientDuration >= 2){
//停止录音
[self.recoder stop];
}
}else{
self.slientDuration = 0;
}
}
-(void) addTime{
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update1)];
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
-(void)removeTime{
[self.displayLink invalidate];
self.displayLink = nil;
}
@end
网友评论