Nuuak
Nuuak

Reputation: 1

UISwitch with AVAudioPlayer

Have problem in playsound section.When i turn switch off - soundchecker change his value to NO,but audioplayer not stopping.What's wrong guys?

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

Upvotes: 0

Views: 170

Answers (1)

Michael Frederick
Michael Frederick

Reputation: 16714

It's not stopping because every time that playsound is called you are creating a NEW AVAudioPlayer. So when you call [audioplayer stop], you are not calling it on the AVAudioPlayer that is currently playing, you are calling it on a new one you just created.

You could add the AVAudioPlayer variable to the header of your class (as a property if you want). Then you could do this:

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

Upvotes: 1

Related Questions