[代码]c#/cpp/oc代码:
01 |
#import <AVFoundation/AVFoundation.h> |
02 |
|
03 |
void CBLediOS::turnOnLed() |
04 |
{ |
05 |
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; |
06 |
if ([device hasTorch]) { |
07 |
[device lockForConfiguration:nil]; |
08 |
[device setTorchMode: AVCaptureTorchModeOn]; |
09 |
[device unlockForConfiguration]; |
10 |
} |
11 |
} |
12 |
void CBLediOS::turnOffLed() |
13 |
{ |
14 |
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; |
15 |
if ([device hasTorch]) { |
16 |
[device lockForConfiguration:nil]; |
17 |
[device setTorchMode: AVCaptureTorchModeOff]; |
18 |
[device unlockForConfiguration]; |
19 |
} |
20 |
|
21 |
} |
这段代码是我昨天刚上传的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];
这两行代码,就是开关闪光灯的代码
注意此代码要在真机下作用