问题
I create the AVAudioPlayer object and play the music within the scene, if i transition through to another scene and then go back to the original scene it creates another object and plays the same soundtrack twice. How do i overcome this ?
NSURL *url = [[NSBundle mainBundle] URLForResource:@"backgroundMusic" withExtension:@"mp3"];
self.backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
self.backgroundMusic.numberOfLoops = -1;
[self.backgroundMusic prepareToPlay];
if (self.backgroundMusic.playing == NO) {
[self.backgroundMusic play];
}
回答1:
Well what do you want to do? Do you want to play music only in that scene? Well then before you transition, stop the avaudioplayer.
[audioplayer stop];
Or, maybe you want to start music in the scene, and let it just continue playing if you leave the scene or go back to the scene?
Well then you would need a seperate wrapper class for your music. Create a class, and just put a call to it to play music. You can check the .playing property to know if music is already playing or not.
来源:https://stackoverflow.com/questions/30002052/avaudioplayer-not-working