Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Device torch turns off when starting AVCaptureSession

I'm using AVCaptureSession to capture video.

I want to light on the torch during the whole session, but once the session is started, the light turns automatically off.

There is a lot of posts here showing how to turn on the torch. It works, unless the capture session is started.

here's the way I start the session

guard let camera = AVCaptureDevice.default(for: .video) else { return }
self.captureSession.beginConfiguration()

let deviceInput = try AVCaptureDeviceInput(device: camera)
self.captureSession.addInput(deviceInput)

let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "com.axelife.axcapturer.samplebufferdelegate"))
self.captureSession.addOutput(videoOutput)

try camera.setLight(on: true)
self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
}

And my code to turn on the light

extension AVCaptureDevice {
    func setLight(on: Bool) throws {
        try self.lockForConfiguration()
        if on {
            try self.setTorchModeOn(level: 1)
        }
        else {
            self.torchMode = .off
        }
        self.unlockForConfiguration()
    }
}

With that code, the light turns on during < 0.5 seconds, and turn back off automatically.

like image 816
Martin Avatar asked Dec 06 '18 18:12

Martin


1 Answers

Ok, I figured out.

The torch simply must be lighted on after the session start.

So instead of:

try camera.setLight(on: true)
self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
}

just do

self.captureSession.commitConfiguration()

DispatchQueue(label: "capturesession").async {
    self.captureSession.startRunning()
    try camera.setLight(on: true)
}
like image 95
Martin Avatar answered Oct 07 '22 00:10

Martin