0%

调整闪光灯和手电筒模式

AVCaptureDevice类可以修改摄像头的闪光灯和手电筒模式.后置摄像头旁的LED灯在拍摄照片时可以作为闪光灯,拍摄视频时可以用作连续灯光(手电筒).本文将实现这一功能.

实现

如在Kcamera中所示,在根View左上角添加一个UISegmentedControl控件,分别设置标题为Off,On,Auto,用来对应闪光灯或手电筒的关闭,开启,自动模式.

在ViewControl中添加对应的事件方法:

//切换闪光灯和手电筒模式
@IBAction func switchFlash(sender: UISegmentedControl) {
    let modeIndex = sender.selectedSegmentIndex
    if self.cameraModel == .Video {
        let mode = AVCaptureTorchMode(rawValue: modeIndex)
        self.captureModel.switchTorch(mode!)
    }else{
        let mode = AVCaptureFlashMode(rawValue: modeIndex)
        self.captureModel.switchFlash(mode!)
    }
    
}

在CaptureModel实现switchFlash()和switchTorch()方法如下:

//MARK:- 拍照闪光灯
func switchFlash(mode:AVCaptureFlashMode) -> Void {
    let device = self.activeVideoInput.device
    if device.isFlashModeSupported(mode) {
        if ((try? device.lockForConfiguration()) != nil) {
            device.flashMode = mode
            device.unlockForConfiguration()
        }
    }
}
//MARK: - 视频手电筒
func switchTorch(mode:AVCaptureTorchMode) -> Void {
    let device = self.activeVideoInput.device
    if device.isTorchModeSupported(mode) {
        if ((try? device.lockForConfiguration()) != nil) {
            device.torchMode = mode
            device.unlockForConfiguration()
        }
    }
}

最后在AppDelegate中didFinishLaunchingWithOptions()方法添加遗漏了的一步:

//设置音频会话
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! session.setActive(true)

音频会话的介绍可参见音频会话

测试

编译运行程序,切换拍摄模式与灯光模式.