audio – [iOS][AVAudioRecorder] Detect and rely noises whereas recording


I’m attempting to jot down an app that might detect when loud noise (i.e clap) has occurred, by way of microphone, and what number of noises have really occur whereas recording customers microphone.

That is the code that I wrote primarily based on the options I discovered:

func startRecording(timerCheckInterval: TimeInterval = 0.3) {
    let audioURL = FileManager.default.demoAudioURL
    print("demoAudioURL: ", audioURL.absoluteString)

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 44100,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
    
    do {
        audioRecorder = attempt AVAudioRecorder(url: audioURL, settings: settings)
        audioRecorder?.isMeteringEnabled = true
        audioRecorder?.delegate = self
        audioRecorder?.prepareToRecord()
        audioRecorder?.file()
        
        timerCancellable = Timer.publish(each: timerCheckInterval, on: .fundamental, in: .default)
            .autoconnect()
            .obtain(on: DispatchQueue.fundamental)
            .sink { [weak self] timestamp in
                guard let self, let audioRecorder = self.audioRecorder else {
                    return
                }

                audioRecorder.updateMeters()
                
                let averagePower = Double(audioRecorder.averagePower(forChannel: 0))
                let peakPower = Double(audioRecorder.peakPower(forChannel: 0))
                
                let alpha: Double = 0.05
                let peakPowerForChannel = pow(10, (0.05 * peakPower))
                self.lowPassResults = alpha * peakPowerForChannel + (1.0 - alpha) * self.lowPassResults
                
                if peakPower > 30 {
                    print(String(format:">>>+++Peak energy: %.2f Common energy: %.2f, currentTime: %.2f", peakPower, averagePower, audioRecorder.currentTime))
                }
            }
    } catch {
        //...
    }
}

this appears to supply me with some information. Nonetheless, if, for instance clap, I clap loud sufficient peakPower might logged to be greater than 30 like 3-4 occasions. I attempted to look into AVAudioEngine, however my noob search was fruitless.
So my query is, is there a solution to inform the distinction when one loud noise ended and new one has begun whereas recording audio? Or perhaps a library that may try this?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles