2016-09-17 185 views
1

我正在尝试使用AVFoundation框架拍摄照片并在我的应用中对其进行分析。我希望它能够每秒自动拍摄一张照片,我该怎么做?AVFoundation每秒拍摄一张照片SWIFT

这是我现在的代码,现在只有在调用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

因此,创建一个NSTimer将触发一次第二,在这的NSTimer的方法调用capturePhoto:

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

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

你timerCalled功能可能是这样的:

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

我应该创建计时器作为成员变量并调用viewDidAppear中的timerCalled? – mawnch

+0

是的,使计时器变量成为一个成员变量,并在viewDidAppear中创建计时器。然后你可以在'viewWillDisappear'中调用'timer.invalidate()'。 –

相关问题