在iPhone X上同时打开手电筒/手电筒和相机

时间:2018-06-12 13:16:32

标签: ios avfoundation 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开始,手电筒就会关闭。

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

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

1 个答案:

答案 0 :(得分:4)

有同样的问题。似乎是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上,你也试过把它关掉再打开#34;工作