在 iPhone 上同时开启 torch/flashlight 和相机 X

Turn on torch/flashlight and camera at the same time on iPhone X

在 iPhone X 上 AVCaptureSession 处于视频模式 运行 时,有没有办法让手电筒保持打开状态?

我有 Swift 4 个代码可以打开手电筒然后开始从相机获取视频帧。我知道它适用于 iPhone 4,5 和 6。但是对于 iPhone X,当我开始捕获会话时手电筒不会亮起。

session = AVCaptureSession()
if self.session.canSetSessionPreset(AVCaptureSession.Preset.inputPriority) {
    self.session.sessionPreset = .inputPriority
}
//This is the wide angle camera device
camera = AVCaptureDevice.default(for: AVMediaType.video)
//I could also use telephoto, same problem
//camera = AVCaptureDevice.default(.builtInTelephotoCamera, for: AVMediaType.video, position: .unspecified)
if camera == nil {
    return
}
if self.camera.isTorchModeSupported(.on) {
    camera.activeFormat = selectBestFormat(camera.formats)
    camera.torchMode = .on
    try? camera.setTorchModeOn(level: 1.0)
    camera.unlockForConfiguration()
}

let cameraInput = try! AVCaptureDeviceInput(device: self.camera)


let videoOutput = AVCaptureVideoDataOutput()
let captureQueue = DispatchQueue(label: "captureQueue")
videoOutput.setSampleBufferDelegate(self, queue: captureQueue)
videoOutput.videoSettings = [
    (kCVPixelBufferPixelFormatTypeKey as AnyObject) as! AnyHashable as! String : Int(kCVPixelFormatType_32BGRA)
]

self.session.addInput(cameraInput)
self.session.addOutput(videoOutput)
//If I don't start the session the torch is on 
self.session.startRunning()

This question也有同样的问题。我的问题是手电筒在 AVCaptureSession 启动后立即关闭。

我试过在开始会话后打开手电筒,我尝试了多种不同的相机配置。我也尝试过使用两种不同的相机镜头。对于所有这些配置,灯都会熄灭。

如果没有解决方案,请让我知道是否有为此记录的错误。或者我会记录一个。

有同样的问题。似乎是 iOS 11/iPhone X

中的错误

我找到了一个解决方法...不是很优雅,但是有效 ;-)

    if let device = captureDevice {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.setTorchLevel(device: device, to: 0)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.setTorchLevel(device: device, to: 1)
        }
    }

即使在 iPhone 上 "Have you tried to turn it off and on again" 也有效