2012-05-03 66 views
0

在播放部分有問題。當我關掉聲音檢測器時,將其值更改爲NO,但音頻播放器不停止。有什麼不對?UISwitch with AVAudioPlayer

-(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; 
    } 
} 

// ------- Playsound ------------------ //

-(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; 
    } 
} 

回答

1

它不停止,因爲每一次那playsound被稱爲你正在創建一個新的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; 
    } 
} 
+0

非常感謝。這是工作。 – Nuuak

+0

很高興聽到它,請接受我的回覆。 –