2011-11-17 43 views
1

我目前正在研究一個小項目,項目/應用程序的含義是,如果您要晃動設備,閃光燈會點燃。如果再次搖動,燈光會熄滅!檢測到運動時切換手電筒

第一個3/4在燈亮或熄滅之間切換工作正常,但在3/4切換之後,由於設備未檢測到搖晃,因此無法打開燈光。

另一個小問題(自iOS 5.0以來)是,如果檢測到動作,閃光燈將閃爍非常短(1秒)而不是開機。這看起來像是短暫的閃光。

我在做什麼錯

檢測抖動:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
    if (event.type == UIEventSubtypeMotionShake) { 
     NSLog(@"shaken, not stirred."); 
     [self playSound]; 
     [self toggleFlashlight]; 
    } 
} 

切換閃光燈ligt:

- (void)toggleFlashlight 
{ 
    AVCaptureDevice *device = 
    [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 

    if ([device hasTorch] && [device hasFlash]){ 

     if (device.torchMode == AVCaptureTorchModeOff) { 

      NSLog(@"It's currently off.. turning on now."); 

      AVCaptureDeviceInput *flashInput = 
      [AVCaptureDeviceInput deviceInputWithDevice:device error: nil]; 

      AVCaptureVideoDataOutput *output = 
      [[AVCaptureVideoDataOutput alloc] init]; 

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

      [session beginConfiguration]; 
      [device lockForConfiguration:nil]; 

      [device setTorchMode:AVCaptureTorchModeOn]; 
      [device setFlashMode:AVCaptureFlashModeOn]; 

      [session addInput:flashInput]; 
      [session addOutput:output]; 

      [device unlockForConfiguration]; 

      [output release]; 

      [session commitConfiguration]; 
      [session startRunning]; 

      [self setAVSession:session]; 
      [session release]; 

     } 
     else { 
      NSLog(@"It's currently on.. turning off now."); 
      [AVSession stopRunning]; 
     } 
    } 
    } 

我會很感激你解決這個問題,我的專業!

回答

2

嗯,我不太瞭解它,但它可能會太快地啓動/停止會話(在最後一次調用它之後調用ToggleFlashLight)。您可能會看到this code here...它建議您一次完成所有操作(除了Torch/FlashModeOn)以創建會話,然後只需執行lock/torchModeOn/flashModeOn/unlock打開並鎖定/ torchModeOff/flashModeOff/unlock即可轉爲關閉。

1

調用你的代碼

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event 

代替motionEnded可以解決你的問題。