2012-07-20 72 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