Detect how long a sound is in iOS

2019-08-14 04:12发布

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.

标签: ios swift
1条回答
男人必须洒脱
2楼-- · 2019-08-14 04:36

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

查看更多
登录 后发表回答