我想使用 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);
}
谢谢
最佳答案
如果不满足条件,则不播放任何声音,但不使计时器失效。这样即使条件一次都没有满足,它也会在间隔内继续触发。
所以:
- (void)playSound {
if(conditionIsMet) {
//code to play your sound
}
}
编辑:
如果你想让声音停止的时间间隔因为条件不满足,那么你只需要把定时器的时间间隔和声音的持续时间调小即可。
关于iOS 我们可以重用 NSTimer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571658/