如何为图像捕捉计时相机闪光灯?

How to time camera flash with image capture?

我想使我的闪光灯在拍照时同步,但不确定如何。我尝试过使用 NSTimer 和 NSSleep 以及其他计时方式,但由于有时相机对焦和拍照的时间比其他时间长,所以闪光灯并不总是完全正确。我将如何做到这一点?

这是我做闪光灯的方法...

func toggleFlash() {
    let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    if (device.hasTorch) {
        device.lockForConfiguration(nil)
        if (device.torchMode == AVCaptureTorchMode.On) {
            device.torchMode = AVCaptureTorchMode.Off
        } else {
            device.setTorchModeOnWithLevel(1.0, error: nil)
        }
        device.unlockForConfiguration()
    }
}

这是我拍照的方式...

func didPressTakePhoto(){

    if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){
        videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {
            (sampleBuffer, error) in

            if sampleBuffer != nil {

                var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                var dataProvider  = CGDataProviderCreateWithCFData(imageData)
                var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)

                var image:UIImage!

                if self.camera == true {
                    image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)

                } else {
                    image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.LeftMirrored)

                }

                self.tempImageView.image = image
                self.tempImageView.hidden = false

            }


        })
    }


}

toggleFlash中,需要设置

device.flashMode = .On

您正在设置 torchMode

更正此问题应该会使闪光灯在 captureStillImageAsynchronouslyFromConnection 期间的正确时间熄灭。