iOS录音
- (void)viewDidLoad {[super viewDidLoad];//設置定時器self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateMeters)];//跟音頻播放的需要設置分類//豬義[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
}- (IBAction)clickRecordBtn:(id)sender {//真機錄制需要設置info.plist進行麥克風的授權說明//開始錄制[self.recorder record];//開啟檢測音量變化self.recorder.meteringEnabled = YES;//開啟定時器[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}- (void)updateMeters{//更新音量變化[self.recorder updateMeters];//獲取瞬時音量 Channel:聲道 -1左聲道 0立體聲 1右聲道float power = [self.recorder peakPowerForChannel:0];NSLog(@"%f", power);//靜默兩秒后就停止靜音if (power < -10) {//累計靜默計數self.muteCount++;if (self.muteCount >= 120) { //靜默兩秒鐘//停止錄音[self.recorder stop];//停止定時器[self.displayLink invalidate];}} else {//有聲音,就重新計數self.muteCount = 0;}
}- (IBAction)clickPauseBtn:(id)sender {//暫停錄制[self.recorder pause];
}- (IBAction)clickStopBtn:(id)sender {//停止錄制[self.recorder stop];
}#pragma mark - 懶加載- (AVAudioRecorder *)recorder{if (_recorder == nil) {//生成的錄音的存放路徑NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"123.caf"];NSDictionary *settings = @{AVSampleRateKey: @44100, AVLinearPCMBitDepthKey: @16};//創建錄音器_recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:path] settings:settings error:nil];/*** AVFormatIDKey 可以設置音樂格式 輔助解析音樂格式類型AVSampleRateKey 采樣率 CD標準音質 44.1kHz 44100次震動/s 人耳 20-20kHzAVNumberOfChannelsKey 聲道數 單聲道0 雙聲道 0左聲道 1右聲道AVLinearPCMBitDepthKey 8Bit 16Bit 32Bit 位深 2^16=66536 計算機就可以將音樂中的聲音最多區分成65536種 位深越深,音質越好*/}return _recorder;
}
總結
- 上一篇: Android app 开发环境搭建
- 下一篇: MATLAB制作简易小动画入门详解