views:

21

answers:

1

I have a problem where I have sound in Menu > Level one. However when I exit Level one and go back to menu the sound won't stop!

What code do I need to terminate the sound?

This is the code I'm using:

- (IBAction) playsound {
NSString *path = [[NSBundle mainBundle] pathForResource:@"imsound" ofType:@"wav"];    
AVAudioPlayer* myAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];    
myAudio.delegate = self;    
myAudio.volume = 1.0;    
myAudio.numberOfLoops = -1;    
[myAudio play];
}
+1  A: 

As the documentation states, -1 will cause it to play repeatedly until you send it a -stop. So the problem becomes "when should I tell it to stop." It's probably a good idea to do so (if it's playing) when you go back.

Because you don't hold a reference to the player (you're leaking it as soon as you leave the -playSound: method, you have no way to tell it to shut up. You should make it an instance variable / property so you can get to it whenever you need to. You're essentially pressing play then tossing the player into the back of someone's truck, then wanting it back so you can turn it off. Should've tied a string to it. ;-)

Proper memory management techniques and use of instance variables are the key causes of your current woes.

Joshua Nozzi