I'm using the audio metering in AVFoundation and I wanted to know if there's a way to figure out how long a sound is. I have my audio recorder setup like this:
func startMeterTimer() {
levelTimer?.invalidate()
levelTimer = CADisplayLink(target: self, selector: "updateMeter")
levelTimer?.frameInterval = 5
levelTimer?.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
}
func stopMeterTimer() {
levelTimer?.invalidate()
levelTimer = nil
}
func updateMeter() {
readLevels()
let avgPower = audioRecorder?.averagePowerForChannel(0)
let peakPower = audioRecorder?.peakPowerForChannel(0)
if peakPower >= -2 {
print("CLAP DETECTED")
soundLogicDelegate?.clapDetected()
}
// print("\(avgPower) + \(peakPower)")
}
func record() -> Bool {
return (audioRecorder?.record())!
}
record and startMeterTImer are called and when I clap my hand, even though I only clap once, I get many print statements of CLAP DETECTED. I was wondering if there was a way to measure how long a method is called from the first time it's called and the last time it's called.
Use the
audioRecorderDidFinishRecording
delegate method, one of it's parameters is an instance ofAVAudioRecorder
which hascurrentTime
property:If you want to check recording time each time
updateMeter()
is called useaudioRecorder?.currentTime