#import <AVFoundation/AVFoundation.h> void CBLediOS::turnOnLed() { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if ([device hasTorch]) { [device lockForConfiguration:nil]; [device setTorchMode: AVCaptureTorchModeOn]; [device unlockForConfiguration]; } } void CBLediOS::turnOffLed() { AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if ([device hasTorch]) { [device lockForConfiguration:nil]; [device setTorchMode: AVCaptureTorchModeOff]; [device unlockForConfiguration]; } }
这段代码是我昨天刚上传的iphone手电筒中的一部分代码
代码示范了如何开启iphone上的闪光灯
AVCaptureDevice必须要引入AVFoundation.framework
defaultDeviceWithMediaType需传入一个字串,在这个例子传入了AVMediaTypeVideo以取得摄像头
AVMediaTypeVideo是ios4.0以上提供的一个const NSString,声明在AVMediaFormat.h.
其他Media Type的声明
NSString *const AVMediaTypeVideo; NSString *const AVMediaTypeAudio; NSString *const AVMediaTypeText; NSString *const AVMediaTypeClosedCaption; NSString *const AVMediaTypeSubtitle; NSString *const AVMediaTypeTimecode; NSString *const AVMediaTypeTimedMetadata; NSString *const AVMediaTypeMuxed;若是要检测装置是否提供该功能,可以透过
- (BOOL)hasMediaType:(NSString *)mediaType
来取得
取得摄像头后,我们可以透过
@property(nonatomic, readonly) BOOL hasTorch
@property(nonatomic, readonly) BOOL hasFlash
来判断该摄像头是否有提供闪光灯
我是要持续开启所以使用Torch Mode
lockForConfiguration跟unlockForConfiguration是配对的API
呼叫lockForConfiguration就可以控制硬件了
控制完毕后要呼叫unlockForConfiguration
[device setTorchMode: AVCaptureTorchModeOn];
[device setTorchMode: AVCaptureTorchModeOff];
这两行代码,就是开关闪光灯的代码
注意此代码要在真机下作用