Reputation: 344
So my audio is working fine if I stay on the same View Controller, the music turns on and off how I want it to. However, when I modal to another view controller with a different header file and return to my original View Controller, I can no longer turn my music on or off. Here is my code:
-(void) viewDidLoad {
//Play Background Music in .1 second after game loads
[self performSelector:@selector(playBackgroundMusic) withObject:nil afterDelay:0.1];
}
-(void) playBackgroundMusic {
//Music int is used so music doesnt play over itself
if (musicInt == 0) {
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/JungleMusic.wav"];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
musicInt = musicInt + 1;
//set our delegate and begin playback
player.delegate = self;
[player play];
player.numberOfLoops = -1;
player.currentTime = 0;
player.volume = 1.0;
}
}
//Used to turn the music on or off
-(IBAction)musicTest:(id)sender{
if (player.playing) {
[player stop];
} else {
[player play];
}
}
I also synthesized my player in the same .m file:
@synthesize player;
And in my .h file I declare the AVAudioPlayer
@interface ViewController1 : UIViewController <AVAudioPlayerDelegate>
{
AVAudioPlayer *player;
}
@property (nonatomic, retain) AVAudioPlayer *player;
Any help figuring this out would be greatly appreciated. I just can't understand why I wouldn't be able to turn my audio on/off after simply modeling to another view controller? Thanks!
Upvotes: 0
Views: 63
Reputation: 131471
Based on our conversation in comments, the answer is that you had a segue to go to the second view controller, and a second segue to go back, which actually created a new instance of the original view controller (and you wound up with three view controllers.)
The solution is to either connect your back button to an IBAction that invokes dismissViewController:animated:completion:
, or to connect the back button to an unwind segue. When you do one of those things the back button dismisses the second view controller and exposes the existing first view controller rather than creating a new copy of the second view controller.
Upvotes: 2