AVFoundation每秒拍摄一次照片SWIFT [英] AVFoundation take picture every second SWIFT

查看:76
本文介绍了AVFoundation每秒拍摄一次照片SWIFT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AVFoundation框架拍照并在我的应用程序中对其进行分析.我希望它每秒自动拍照一次,怎么办?

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?

这是我当前的代码,现在仅在调用capturePhoto()时才拍照.

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

  }
}

我应该改变什么?

推荐答案

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

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)

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

Your timerCalled function might look like this:

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

这篇关于AVFoundation每秒拍摄一次照片SWIFT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆