skip to Main Content

I want to perform something using the AVCaptureVideoDataOutputSampleBufferDelegate protocol. But since it captures every frame at (I think) 30 frames per second, it performs the method 30 times in 1 second and I don’t want that. What I want to do is only to perform the method for let’s say every 1 second at a time. So far my code looks like this:

func captureOutput(_ output: AVCaptureOutput,
                   didOutput sampleBuffer: CMSampleBuffer,
                   from connection: AVCaptureConnection) {
    // ... perform something
    // ... wait for a second
    // ... perform it again
    // ... wait for another second
    // ... and so on
}

How can I manage to do this?

2

Answers


  1. You can use Timer for that.

    Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
        let randomNumber = Int.random(in: 1...20)
        print("Number: (randomNumber)")
    
        if randomNumber == 10 {
            timer.invalidate()
        }
    }
    
    Login or Signup to reply.
  2. You can add a counter and only perform your code every n steps, like eg when you want to perform your code every 30 times the function is called:

    var counter: Int = 0
    
    ...
    
    func captureOutput(_ output: AVCaptureOutput,
                       didOutput sampleBuffer: CMSampleBuffer,
                       from connection: AVCaptureConnection) {
        if counter%30 == 0 {
            // perform your code
        }
        counter += 1
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search