gpt4 book ai didi

ios - 如何知道 AVCaptureDevice 手电筒灯何时关闭?

转载 作者:行者123 更新时间:2023-11-29 11:51:56 24 4
gpt4 key购买 nike

我有一个基于 AVCam 的 View Controller ,我添加了一个 UIButton 来切换手电筒。这是执行该操作的代码:

- (IBAction)toggleTorchLight:(id)sender {
// See: http://stackoverflow.com/questions/11726543/how-to-turn-flashlight-on-off-using-one-button
AVCaptureDevice *flashLight = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([flashLight isTorchAvailable] && [flashLight isTorchModeSupported:AVCaptureTorchModeOn]){
if ([flashLight lockForConfiguration:nil]){
if ([flashLight isTorchActive]) {
[flashLight setTorchMode:AVCaptureTorchModeOff];
[(UIButton *)sender setTintColor:[UIColor blackColor]];
}
else {
[flashLight setTorchMode:AVCaptureTorchModeOn];
[(UIButton *)sender setTintColor:[UIColor yellowColor]];
}
[flashLight unlockForConfiguration];
}
}

您会注意到,当灯亮起时,我将按钮变成了黄色。问题是当应用程序发送到后台时,手电筒灯也会关闭,当 View Controller 发生变化时,当出现警报 View Controller 时等。这些事件会关闭手电筒灯,但我还需要制作按钮又黑了。

有没有一种简单的方法,比如在灯熄灭时接收通知,而不是针对每个单独的场景将按钮设为黑色?我试过 AVCaptureDeviceWasDisconnectedNotification,覆盖 becomeFirstResponderviewDidDisappear,但都没有用。

有什么建议吗?

最佳答案

首先定义一个上下文地址:

static void * TorchActiveContext = &TorchActiveContext;

然后在addObservers方法中:

AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[videoDevice addObserver:self forKeyPath:@"torchActive" options:NSKeyValueObservingOptionNew context:TorchActiveContext];

removeObservers 方法中:

AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[videoDevice removeObserver:self forKeyPath:@"torchActive" context:TorchActiveContext];

observeValueForKeyPath

if (context == TorchActiveContext) {
UIColor *color = ((AVCaptureDevice*)object).torchActive ? [UIColor yellowColor] : [UIColor blackColor];
[self.torchLightButton setTintColor:color];
}

关于ios - 如何知道 AVCaptureDevice 手电筒灯何时关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40750787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com