0

playsound 部分有问题。当我关闭开关时 - soundchecker 将他的值更改为 NO,但 audioplayer 没有停止。出了什么问题?

-(IBAction)Settings {
    if(settingsview==nil) {
        settingsview=[[UIView alloc] initWithFrame:CGRectMake(10, 130, 300, 80)];
        [settingsview setBackgroundColor:[UIColor clearColor]];

        UILabel *labelforSound = [[UILabel alloc]initWithFrame:CGRectMake(15, 25, 70, 20)];
        [labelforSound setFont:[UIFont systemFontOfSize:18]];
        [labelforSound setBackgroundColor:[UIColor clearColor]];
        [labelforSound setText:@"Sound"];

        SoundSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(10, 50, 20, 20)];
        SoundSwitch.userInteractionEnabled = YES;

        if(soundchecker == YES) [SoundSwitch setOn:YES];
        else [SoundSwitch setOn:NO];
        [SoundSwitch addTarget:self action:@selector(playsound:) forControlEvents:UIControlEventValueChanged];

        [settingsview addSubview:labelforSound];
        [settingsview addSubview:SoundSwitch];
        [self.view addSubview:settingsview];
   }

   else {
        [settingsview removeFromSuperview];
        [settingsview release];
        settingsview=nil;
   }
}

// - - - -播放声音 - - - - - - - - - //

-(void)playsound:(id) sender {
    NSString *pathtosong = [[NSBundle mainBundle]pathForResource:@"Teachme" ofType:@"mp3"];
    AVAudioPlayer* audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathtosong] error:NULL];
    if(SoundSwitch.on) {
        [audioplayer play];
        soundchecker = YES;
    }

    if(!SoundSwitch.on) {
        [audioplayer stop];
        soundchecker = NO;
    }
}
4

1 回答 1

1

它不会停止,因为每次playsound调用你都在创建一个 NEW AVAudioPlayer。因此,当您调用 时[audioplayer stop],您不是在AVAudioPlayer当前正在播放的播放器上调用它,而是在刚刚创建的新播放器上调用它。

您可以将 AVAudioPlayer 变量添加到类的标题中(如果需要,可以作为属性)。然后你可以这样做:

-(void)playsound:(id) sender
{ 
    if(SoundSwitch.on) 
    {
        if(!audioPlayer) {
             NSString *pathtosong = [[NSBundle mainBundle]pathForResource:@"Teachme" ofType:@"mp3"];
             audioplayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:pathtosong] error:nil];
        }
        [audioplayer play];
        soundchecker = YES;
    } else {
        if(audioPlayer && audioPlayer.isPlaying) {
             [audioplayer stop];
        }
        soundchecker = NO;
    }
}
于 2012-05-03T19:23:48.673 回答