AVFoundation take picture every second SWIFT

泄露秘密 提交于 2021-02-07 10:38:19

问题


I'm trying to use AVFoundation framework to take a picture and analyze it in my app. I want it to take a picture every second automatically, how do I do that?

Here is my current code, right now it takes a picture only when call capturePhoto().

func setupSession() {
  session = AVCaptureSession()
  session.sessionPreset = AVCaptureSessionPresetPhoto

  let camera = AVCaptureDevice
     .defaultDeviceWithMediaType(AVMediaTypeVideo)

  do { input = try AVCaptureDeviceInput(device: camera) } catch { return }

  output = AVCaptureStillImageOutput()
  output.outputSettings = [ AVVideoCodecKey: AVVideoCodecJPEG ]

  guard session.canAddInput(input)
     && session.canAddOutput(output) else { return }

  session.addInput(input)
  session.addOutput(output)

  previewLayer = AVCaptureVideoPreviewLayer(session: session)

  previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
  previewLayer!.connection?.videoOrientation = .Portrait

  view.layer.addSublayer(previewLayer!)

  session.startRunning()
}

func capturePhoto() {
  guard let connection = output.connectionWithMediaType(AVMediaTypeVideo) else { return }
  connection.videoOrientation = .Portrait

  output.captureStillImageAsynchronouslyFromConnection(connection) { (sampleBuffer, error) in
     guard sampleBuffer != nil && error == nil else { return }

     let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
     guard let image = UIImage(data: imageData) else { return }

     //do stuff with image

  }
}

What should I change?


回答1:


So create an NSTimer that fires once a second, and in that NSTimer's method call capturePhoto:

Create a timer that fires once a second:

var cameraTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, 
  target: self, 
  #selector(timerCalled(_:)), 
  userInfo: nil, 
  repeats: true)

Your timerCalled function might look like this:

func timerCalled(timer: NSTimer) {
  capturePhoto()
}


来源:https://stackoverflow.com/questions/39551466/avfoundation-take-picture-every-second-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!