Welcome 微信登录

首页 / 操作系统 / Linux / iPhone开发基础教程:LED闪光灯控制

  1. #import <AVFoundation/AVFoundation.h>   
  2.   
  3. void CBLediOS::turnOnLed()  
  4. {  
  5.     AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];  
  6.     if ([device hasTorch]) {  
  7.         [device lockForConfiguration:nil];  
  8.         [device setTorchMode: AVCaptureTorchModeOn];  
  9.         [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.frameworkdefaultDeviceWithMediaType需传入一个字串,在这个例子传入了AVMediaTypeVideo以取得摄像头AVMediaTypeVideo是ios4.0以上提供的一个const NSString,声明在AVMediaFormat.h.其他Media Type的声明
  1. NSString *const AVMediaTypeVideo;  
  2. NSString *const AVMediaTypeAudio;  
  3. NSString *const AVMediaTypeText;  
  4. NSString *const AVMediaTypeClosedCaption;  
  5. NSString *const AVMediaTypeSubtitle;  
  6. NSString *const AVMediaTypeTimecode;  
  7. NSString *const AVMediaTypeTimedMetadata;  
  8. NSString *const AVMediaTypeMuxed;  
若是要检测装置是否提供该功能,可以透过- (BOOL)hasMediaType:(NSString *)mediaType来取得取得摄像头后,我们可以透过@property(nonatomic, readonly) BOOL hasTorch@property(nonatomic, readonly) BOOL hasFlash来判断该摄像头是否有提供闪光灯我是要持续开启所以使用Torch ModelockForConfiguration跟unlockForConfiguration是配对的API呼叫lockForConfiguration就可以控制硬件了控制完毕后要呼叫unlockForConfiguration[device setTorchMode: AVCaptureTorchModeOn];[device setTorchMode: AVCaptureTorchModeOff];这两行代码,就是开关闪光灯的代码注意此代码要在真机下作用