views:

36

answers:

1

I have a class in which I have an audio player. In class B, I have a switch, from where I want to take control of play and stop of background music.

I am not able to stop and play music through switch. this is my audio player at viewdidload of class A

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/bgmusic.wav", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
if (audioPlayer == nil) NSLog([error description]);
else [audioPlayer play];

this is swtich of class B

-(IBAction) musicValueChanged:(id)sender{    
if (musicSwitch.on) { 
    isStopped = FALSE;
    firstViewController.player.currentTime = 0;
    [firstViewController.audioPlayer play];
 }else {
    [firstViewController.audioPlayer volume:0];
 }
}

How can i do it?

+1  A: 

As long as the method is called and musicSwitch.on has a value, this should work:

-(IBAction) musicValueChanged:(id)sender{

if (musicSwitch.on) { 
    isStopped = FALSE;
    firstViewController.player.currentTime = 0;
    [firstViewController.audioPlayer play];
 }else {
    [firstViewController.audioPlayer stop];
 }
}

See the AVAudioPlayer docs.

TechZen