【发布时间】:2016-09-17 20:34:15
【问题描述】:
我正在尝试使用 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
}
}
我应该改变什么?
【问题讨论】:
标签: ios swift camera avfoundation avcapturesession