AVCaptureSession关闭手电筒

时间:2019-04-18 18:28:05

标签: swift avcapturesession

我正在尝试使用Swift 5构建新的应用程序,并试图在打开闪光灯的情况下捕获视频图像。闪光灯闪烁一次,然后关闭。有什么办法强迫它吗?

我尝试将闪光灯放在各个地方都没有成功(在captureSession.startRunning之前和之后) 下面是加载的视图:

override func viewDidLoad() {
       super.viewDidLoad()

       configure()
       captureSession.startRunning()
       guard let captureDevice = AVCaptureDevice.default(for: .video) else {
           print("Failed to get the camera device")

           return
       }

       captureDevice.toggleTorch(on: true)
   }
        // Get the back-facing camera for capturing videos
        guard let captureDevice = AVCaptureDevice.default(for: .video) else {
            print("Failed to get the camera device")

            return
        }

        do {

            // Get an instance of the AVCaptureDeviceInput class using the previous device object.
            let input = try AVCaptureDeviceInput(device: captureDevice)


            // Set the input device on the capture session.
            captureSession.addInput(input)
            let videoDataOutput = AVCaptureVideoDataOutput()
            videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "imageRecognition.queue"))
                videoDataOutput.alwaysDiscardsLateVideoFrames = true
                captureSession.addOutput(videoDataOutput)


        } catch {
            // If any error occurs, simply print it out and don't continue any more.
            print(error)
            return
        }

        // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoPreviewLayer?.frame = view.layer.bounds
        view.layer.addSublayer(videoPreviewLayer!)
        // Bring the label to the front
        descriptionLabel.text = "Looking for objects..."
        view.bringSubview(toFront: descriptionLabel)
        }
extension AVCaptureDevice {
    func toggleTorch(on: Bool) {
        guard let device = AVCaptureDevice.default(for: .video) else { return }

        if device.hasTorch {
            do {
                try device.lockForConfiguration()

                if on == true {
                    device.torchMode = .on
                } else {
                    device.torchMode = .off
                }

                device.unlockForConfiguration()
            } catch {
                print("Torch could not be used")
            }
        } else {
            print("Torch is not available")
        }
    }
}

任何帮助将不胜感激!

0 个答案:

没有答案