Edited
i've got a sound in my app which begins to play when the app is started. further I've got two method to play and stop the sound:
-(void)playBgMusic {
NSString *path = [[NSBundle mainBundle] pathForResource:@"bgmusic" ofType:@"aif"];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
[defaults setBool:NO forKey:@"isQuiet"]; }
-(void)stopMusic {
[theAudio stop];
[defaults setBool:YES forKey:@"isQuiet"]; }
Now I've got different viewControllers and in my mainView there's a button which stops/starts the music (depends on wheter music is playing or not).
So 开发者_StackOverflow社区I've got:
-(IBAction)check {
isquiet = [defaults boolForKey:@"isQuiet"];
if (isquiet == YES) {
[self playBgMusic];
// Change button to indicate music is playing
}
else {
[self stopMusic];
// Change the button to indicate music has stopped...
}
}
Now there's a problem. The sound plays when the app is started, after that I can press the button and the sound is stopped but then I cant start it again. I've put NSLogs in the code and saw that the BOOL is still NO after pressing the stopButton.
Where's my mistake?
This is not an answer, strictly speaking, but hopefully it'll set you on the right track...
Add some logging (either via NSLog(...)
or add logging breakpoints) to the NO and YES cases of the above code that outputs the value of isquiet
. Then you can see which code paths are invoked when you press the button under different scenarios.
You are on the right track, the only thing missing is actually saving the bool value back to NSUserDefaults when you start/stop playing, so everytime you click the button and read it, you get the correct value.
Give this a try and see if it helps:
-(IBAction)check
{
BOOL isQuiet = [userDefaults boolForKey:@"isQuiet"];
if (isQuiet)
{
[self playBgMusic];
// Change button to indicate music is playing
} else {
[self stopBgMusic];
// Change the button to indicate music has stopped...
}
}
Then in your playBgMusic
method, add the following:
[userDefaults setBool:NO forKey:@"isQuiet"];
And in your spotBgMusic
method, add the following:
[userDefaults setBool:YES forKey:@"isQuiet"];
精彩评论