简体   繁体   中英

Detect how long a sound is in iOS

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 of AVAudioRecorder which has currentTime property:

The time, in seconds, since the beginning of the recording. (read-only)

If you want to check recording time each time updateMeter() is called use audioRecorder?.currentTime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM