我正在尝试用AVAudioRecorder录制音频.我需要创建一个这样的简单波形:
当用户对着麦克风说话时,圆圈表示用户语音的等级.我尝试使用此代码测量语音,但代码未检测到任何缓冲区而无法正常工作:
func levelTimerCallback(timer:Timer) { //we have to update meters before we can get the metering values audioRecorder.updateMeters() //print to the console if we are beyond a threshold value. Here I've used -7 if audioRecorder.averagePower(forChannel: 1) > -7 { print(" level I'm hearin' you in dat mic ") print(audioRecorder.averagePower(forChannel: 0)) } }
录制音频:
func startRecording() { let audioSession = AVAudioSession.sharedInstance() do { // Audio Settings settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC),AVSampleRateKey: 12000,AVNumberOfChannelsKey: 1,AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] audioRecorder = try AVAudioRecorder(url: self.directoryURL(),settings: settings) audioRecorder.delegate = self audioRecorder.prepareToRecord() audioRecorder.isMeteringEnabled = true } catch { finishRecording(success: false) } do { try audioSession.setActive(true) audioRecorder.record() TIMERRRRR = Timer.scheduledTimer(timeInterval: 0.02,target: self,selector: #selector(ViewController.levelTimerCallback),userInfo: nil,repeats: true) } catch { } }
解决方法
我能看到的两个问题.
第一个是您在函数levelTimerCallback中使用错误的通道编号进行测试.您的测试应该是针对频道0.
另一个是-7的值实际上非常响亮. averagePower返回介于-160和0之间的浮点数.尝试针对-160进行测试以开始并增加该值以降低灵敏度.
这会将您的测试更改为:
if audioRecorder.averagePower(forChannel: 1) > -160 { ... }
输入只有一个通道,计数从0开始.稍后您在调用audioRecorder.averagePower时就可以了.
要获得线性比例,您需要进行插值.更改比例值以更改范围.比例将介于0和比例之间.
let lowerLimit: Float = -100.0 func levelTimerCallback(timer:Timer) { audioRecorder.updateMeters() let power = audioRecorder.averagePower(forChannel: 0) if power > lowerLimit { // proportion will have a value between 0 and scale let scale: Float = 10.0 let proportion = -scale * (power - lowerLimit) / lowerLimit } }
编辑:修正比例计算