7

我正在开发一个简单的应用程序,我需要让我的相机闪光灯模式持续开启,而不仅仅是在捕获图像时。并且操作模式应该是相机而不是视频录制。可能吗 ?如果是这样比如何。请帮我一些代码

4

2 回答 2

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];
    }
} 
}

资源

于 2012-10-30T19:36:53.543 回答
2

将此用于 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)
        }
    }
}
于 2017-11-30T11:45:40.303 回答