我目前正在使用下面的代码来打开和关闭我的 iPhone 4 LED 灯,它工作得很好,但唯一的问题是每次我打开 LED 时都会有轻微的延迟。但它会立即关闭。我需要它立即触发来实现类似频闪的功能,因为它更方便。
我注意到,在 Apple 的相机应用程序和许多其他应用程序中,当您按下电源按钮时,LED 会立即打开和关闭。
我尝试将一些对象(如“ session ”和“设备”)作为实例变量添加到我的 View Controller 中,以便让 iPhone 在加载时创建这些对象,但是我没有运气得到让它工作。
我也尝试过查看苹果 WWDC 示例代码,但我似乎无法破译他们的复杂代码。有人可以帮我解决这个问题吗?我已经尝试了大约 4 天才能让它发挥作用。
.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface FlashlightViewController : UIViewController {
AVCaptureSession *torchSession;
}
@property (nonatomic, retain) AVCaptureSession * torchSession;
- (void) toggleTorch;
@end
.m
#import "FlashlightViewController.h"
@implementation FlashlightViewController
@synthesize torchSession;
- (void)dealloc
{
[torchSession release];
[super dealloc];
}
- (void)viewDidLoad
{
[self toggleTorch];
[super viewDidLoad];
}
- (void) toggleTorch
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash])
{
if (device.torchMode == AVCaptureTorchModeOff)
{
NSLog(@"It's currently off.. turning on now.");
AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
[session addInput:flashInput];
[session addOutput:output];
[device unlockForConfiguration];
[output release];
[session commitConfiguration];
[session startRunning];
[self setTorchSession:session];
[session release];
}
else {
NSLog(@"It's currently on.. turning off now.");
[torchSession stopRunning];
}
}
}
最佳答案
在应用程序初始化或 View 加载期间,在打开闪光灯 LED 之前,执行除闪光灯配置 block 之外的所有操作(所有 session 和设备配置内容)。
然后,当您想要打开 LED 时,只需将手电筒模式设置为打开即可。像这样的东西:
[self.myDevice lockForConfiguration:nil];
[self.myDevice setTorchMode:AVCaptureTorchModeOn];
[self.myDevice setFlashMode:AVCaptureFlashModeOn];
[self.myDevice unlockForConfiguration];
确保 myDevice 在初始化期间是正确配置的属性。
关于iphone - 如何让 iPhone 4 LED 灯瞬间发光?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983032/