1

我正在尝试设置通过 UISwitch 启用的秒表警报。我希望在计时器启动后 x 秒后触发警报。我有一个 ivar int 变量 (timerCount),它保存了经过的秒数,我想根据该 ivar 播放声音。当计时器开始并启用开关时,我希望播放器会在 10 秒后开火,但事实并非如此。我知道“if 语句”是罪魁祸首,因为当我删除它时,AVPlayer 将在启用开关时播放 wav 文件。我只需要另一组眼球来看看这个并弄清楚我错过了什么。这是代码片段:

- (IBAction)timerSound{

    if (voiceSwitch.on){

    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"horn"
                                                         ofType:@"wav"];

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];

    player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];

    if (timerCount == 10)

    [self.player play];

    }

    else {
        [self.player stop];
    }
}
4

1 回答 1

1

You are looking for playAt:.

Example based on yours –</p>

- (IBAction)valueChanged:(id)sender {
    UISwitch *aSwitch = (UISwitch*)sender;
    if ( aSwitch.on ) {
        NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"horn"
                                                                  ofType:@"wav"];

        NSURL *fileURL = [NSURL fileURLWithPath:soundFilePath];

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL 
                                                                error:nil];

        [audioPlayer playAtTime:(audioPlayer.deviceCurrentTime + 3)];
    } else {
        [audioPlayer stop];
    }
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    [self.theSwitch setOn:NO animated:YES];

    [player release];
}
于 2011-05-23T18:11:59.543 回答