0

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);

}

ありがとうございました

4

1 に答える 1

3

条件が満たされていない場合は、音を鳴らさないでください。ただし、タイマーを無効にしないでください。そうすれば、条件が一度も満たされない場合でも、間隔を置いて発砲し続けます。

それで:

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

編集:

条件が満たされていないために音が止まる間隔を作りたい場合は、タイマーの時間間隔と音の持続時間を短くするだけです。

于 2012-07-20T01:31:23.250 に答える