Reputation: 638
When i switch views the music keep playing the the background what is fine with my app. But when the user comes back to the initial view the music starts again over the original one so the user hears the music double. I have already got some code to check whether the sound is already playing but it doesnt work. :(
Any thoughts?
if (audioPlayer.playing == 0 ) {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/CheeZeeLab.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
audioPlayer.volume = 1;
[audioPlayer prepareToPlay];
[audioPlayer stop];
if (audioPlayer == nil)
NSLog(@"werkt niet");
else
[audioPlayer play]; }
else{
}
Upvotes: 0
Views: 92
Reputation: 443
Depending on how you have set up the AVAudioPlayer, with manual setter and getter, with property or even in the constructor. You are confronted with some issues.
When you initialize the ViewController you are allocating an AVAudioPlayer, and if it keeps playing it's not being deallocated, and still retained. And the ViewController won't be deallocated either until every property's retain count is 0.
After going back to the main view, and trying to set up the same ViewController again, my guess is that you are not trying to push the same instance to the stack. But rather making a new instance and pushing that one onto the stack? And that also makes a AVAudioPlayer.
This is ofc a bit of guesswork as a can't see you entire code. But if this is the case, I think you could set things up a bit better. Make sure that the ViewController gets properly deallocated and releasing all it's properties before making a new instance to push to the stack.
Upvotes: 0
Reputation: 89519
I bet your problem is in how you transition back to your initial view.
If you're pushing (or doing a segue from the child back to the parent... i.e. a circular segue), you're creating a new instance of your parent view controller.
And creating a new instance starts a fresh version of the audio player playing that sound.
You need to properly pop the view to go back to the previous view controller.
Upvotes: 0