2012-05-03 5 views
0

私はスイッチをオフにすると、サウンドチェッカーは値をNOに変更しますが、オーディオプレイヤーは停止しません。何が間違っていますか?AVAudioPlayerのUISwitch

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

喜んでそれを聞いて、私の応答を受け入れてください。 –