- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/Intro2.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
}
My background music plays when the app loads the initial view controller, and loops fine. When I leave the initial view controller the music continues to play throughout the app, I would like for the music to stop when I leave the initial view controller.
Also, maybe it’s unrelated, but I have an Issue (yellow !) on this line of code:
NSLog([error description]);
If the music continues to play, that means that the view controller is still retained. It is for example the root view controller of your navigation view controller.
To stop the music when the view controller is no longer displayed, you should use the method
viewWillDisappear:If you want the music to resume when the view controller is displayed again, use the method
viewWillAppear:To remove the warning, change the line:
into: