我目前正在使用下面的代码来打开和关闭我的 iPhone 4 LED 灯,它工作得很好,但唯一的问题是每次我打开 LED 时都会有轻微的延迟。但是它会立即关闭。我需要它立即触发以实现类似频闪的功能,并且因为它更方便。
我注意到在 Apple 的相机应用程序和许多其他应用程序中,当您按下电源按钮时,LED 会立即打开和关闭。
我尝试将“会话”和“设备”等一些对象作为实例变量添加到我的视图控制器中,以便让 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];
}
}
}