使用avfoundation检测db

时间:2018-02-08 16:14:30

标签: swift avfoundation

您好我正在尝试监控数据库。录音不是我的主要目的。我正在使用avfoundation来做到这一点。下面是我尝试打印数据库的代码。但是我只得到-160dbfs。有什么东西我错过了吗?谢谢!

   override func viewDidLoad() {
        super.viewDidLoad()
        recordingSession = AVAudioSession.sharedInstance()
        AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
            if hasPermission{
                print("Accpeted")
            }
        }
        let filename = getDocumentsDirectory().appendingPathComponent("recording.m4a")
        let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey:12000,AVNumberOfChannelsKey:1,AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue]
        do{
            audioRecorder = try AVAudioRecorder(url: filename,settings:settings)
            audioRecorder.delegate = self
            audioRecorder.isMeteringEnabled = true
            timerOne()
        }catch{
            print("failed to initialize")
        }
        audioRecorder.record()
        print(audioRecorder.isRecording)
    }

    func timerOne() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateMonitorDb), userInfo: nil, repeats: true)
    }

    @objc func updateMonitorDb(){
        audioRecorder.updateMeters()
        let monitorDb = audioRecorder.averagePower(forChannel: 1)
        print(monitorDb)
    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }

1 个答案:

答案 0 :(得分:0)

您只录制1个频道,averagePower(forChannel:)基于0。

@objc func updateMonitorDb(){
    audioRecorder.updateMeters()
    let monitorDb = audioRecorder.averagePower(forChannel: 0)
    print(monitorDb)
}