AVFoundation每隔一秒SWIFT拍照

时间:2016-09-17 20:34:15

标签: ios swift camera avfoundation avcapturesession

我正在尝试使用AVFoundation框架拍照并在我的应用中进行分析。我想让它每秒自动拍一张照片,我该怎么做?

这是我当前的代码,现在它仅在调用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

  }
}

我应该改变什么?

1 个答案:

答案 0 :(得分:1)

因此,创建一个每秒触发一次的NSTimer,并在该NSTimer的方法中调用capturePhoto:

创建一个每秒触发一次的计时器:

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

您的timerCalled函数可能如下所示:

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