我正在开发一个简单的应用程序,我需要让我的相机闪光模式不仅在拍摄图像时持续开启。而操作方式应该是相机而不是视频录制。可能吗 ?如果是这样的话。请帮我一些代码
答案 0 :(得分:8)
您可以使用以下方法来打开和关闭相机闪光灯。
- (void)toggleFlashlight
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device.torchMode == AVCaptureTorchModeOff)
{
// Create an AV session
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Create device input and add to current session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];
// Create video output and add to current session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
// Start session configuration
[session beginConfiguration];
[device lockForConfiguration:nil];
// Set torch to on
[device setTorchMode:AVCaptureTorchModeOn];
[device unlockForConfiguration];
[session commitConfiguration];
// Start the session
[session startRunning];
// Keep the session around
[self setAVSession:session];
[output release];
}
else
{
[AVSession stopRunning];
[AVSession release],
AVSession = nil;
}
}
您还可以将以下方法与相机显示一起使用
- (void) toggleFlashlight {
// check if flashlight available
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (device.torchMode == AVCaptureTorchModeOff)
{
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
}
else
{
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
}
[device unlockForConfiguration];
}
}
}
答案 1 :(得分:1)
将此用于Swift 4
func toggleFlash() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video)
else {return}
if device.hasTorch {
do {
try device.lockForConfiguration()
if device.torchMode == AVCaptureDevice.TorchMode.on {
device.torchMode = AVCaptureDevice.TorchMode.off
//AVCaptureDevice.TorchModeAVCaptureDevice.TorchMode.off
} else {
do {
try device.setTorchModeOn(level: 1.0)
} catch {
print(error)
}
}
device.unlockForConfiguration()
} catch {
print(error)
}
}
}