2012-07-20 70 views
0

我想使用NSTimer(或者如果您有更好的建議)在設備拔出或未知時播放聲音。但是,如果用戶重新插入設備,聲音應立即停止。iOS可以重複使用NSTimer

這裏是我的代碼,但它似乎並沒有表現爲我描述它,

- (void)currentBatteryState 
{ 
    UIDevice *device = [UIDevice currentDevice]; 
    switch(device.batteryState) { 
     case UIDeviceBatteryStateUnknown: 
      currentBatteryStatusLabel.text = @"Unknown"; 
      if ([batteryControlTimer isValid]) { 
       [batteryControlTimer invalidate]; 
       batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES]; 
      } else { 
       batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES]; 
      } 
      break; 
     case UIDeviceBatteryStateUnplugged: 
      currentBatteryStatusLabel.text = @"Unplugged"; 
      if ([batteryControlTimer isValid]) { 
       [batteryControlTimer invalidate]; 
       batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES]; 
      } else { 
       batteryControlTimer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(playSound) userInfo:nil repeats:YES]; 
      } 
      break; 
     case UIDeviceBatteryStateCharging: 
      currentBatteryStatusLabel.text = @"Charging"; 
      [batteryControlTimer invalidate]; 
      break; 
     case UIDeviceBatteryStateFull: 
      currentBatteryStatusLabel.text = @"Full"; 
      [batteryControlTimer invalidate]; 
      break; 
    } 
} 

- (void) playSound 
{ 
    CFBundleRef mainBundle = CFBundleGetMainBundle(); 
    CFURLRef soundFileURLRef; 
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"siren_1", CFSTR ("mp3"), NULL); 
    UInt32 soundID; 
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID); 
    AudioServicesPlaySystemSound(soundID); 

} 

謝謝

+0

定義*重用*。 – 2012-07-20 01:31:33

+0

使用相同的變量(batteryControlTimer)而不必創建一個新變量。 batteryControlTimer在h文件中,我們綜合了實現文件中的屬性。 – 2012-07-20 02:00:02

回答

3

如果條件不滿足,不玩任何聲音,但不要使計時器無效。這樣,即使條件不滿足一次,它也會在間隔時間繼續發射。

所以:

- (void)playSound { 
    if(conditionIsMet) { 
     //code to play your sound 
    } 
} 

編輯:

如果你想在這聲音能停止,因爲條件不符合的時間間隔,那麼你只需要做出定時器的時間間隔並且聲音的持續時間更短。

+0

我不確定我是否理解這個問題。如果條件改變,您想要在播放時播放聲音? – 2012-07-20 01:34:10

+0

是的,我想根據條件啓動和停止聲音 – 2012-07-20 01:59:07

+0

將邏輯放在playSound代碼中而不是將playSound包裝在邏輯中是個好主意嗎? – 2012-07-20 02:33:35