2012-05-03 3 views
0

playsound 섹션에 문제가 있습니다. 스위치를 끄면 사운드 크리커가 값을 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; 
    } 
} 

// -------시 소리 ------------------ //

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

다행이라면 제 대답을 받아주십시오. –