- #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];
這兩行代碼,就是開關閃光燈的代碼
注意此代碼要在真機下作用