I currently have background music playing in my application.
in:
-(void)viewDidLoad
I start the music, using:
[self LoadMusic];
This basically starts up music buffers it then if the settings state that ‘Sound is On’ the music starts.
The problem i have is when i move views, the music continues to play (as it should) but when you go back to the view controller where the music was first started, it actives again.
So you end up with the same music looping on top of each other.
I have tried a few things such as:
if(MusicPlay.playing){
// do nothing
}else{
// start music
[self LoadMusic];
}
This is the code for loadMusic
- (void) LoadMusic{
//Notification for stoping
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:@"StopMusic" object:nil];
//Notification for playing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playMusic) name:@"PlayMusic" object:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *SoundSwitch = [defaults stringForKey:@"Sound_EnabledS"];
// grab the path to the caf file
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: @"Menu_Loop"
ofType: @"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
// create a new AVAudioPlayer initialized with the URL to the file
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
// set our ivar equal to the new player
self.MusicPlay = newPlayer;
// preloads buffers, gets ready to play
[MusicPlay prepareToPlay];
MusicPlay.numberOfLoops = -1; // Loop indefinately
if ([SoundSwitch isEqualToString:@"1"]){
[self.MusicPlay play]; // Plays the sound
}else{
[self.MusicPlay stop]; // Stops the sound
}
}
But this does not work as it does not see MusicPlay.playing is only true once the view has been ‘restarted’
If anyone has a good way to solved this problem.
Please let me know.
Thank you.
Your code should also work but check with following code