激活手电筒应用程序的LED

时间:2010-07-15 07:02:39

标签: iphone ios cocoa-touch

我正在尝试为我的iPhone制作一个手电筒应用程序。我有一台iPhone 4,想在我的iPhone上使用LED作为我的项目。任何人都可以帮我开始吗?

2 个答案:

答案 0 :(得分:30)

以下是您现在可用于打开或关闭LED的较短版本:

- (void)torchOnOff: (BOOL) onOff
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: onOff ? AVCaptureTorchModeOn : AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

更新:( 2015年3月)

您还可以设置手电筒的亮度:

- (void)setTorchToLevel:(float)torchLevel
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (torchLevel <= 0.0) {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        else {
            if (torchLevel >= 1.0)
                torchLevel = AVCaptureMaxAvailableTorchLevel;
            BOOL success = [device setTorchModeOnWithLevel:torchLevel   error:nil];
        }
        [device unlockForConfiguration];
    }
}

答案 1 :(得分:15)

使用以下内容:

AVCaptureSession * session = [[AVCaptureSession alloc] init];

[session beginConfiguration];

AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn]; 
[device unlockForConfiguration];

AVCaptureDeviceInput * flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if (flashInput){
    [session addInput:flashInput];
}
    AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc] init];
    [session addOutput:output];
        [output release];
    [session commitConfiguration];  
    [session startRunning];
}
[self setTorchSession:session];
[session release];

(来自iPhoneDevSDK上的discussion