问题
Hi I was wondering if there was a way to use an AVAudioPlayer across multiple scenes and change the volume. I'm currently placing it in my gameViewController which is the controller for all of my application's scenes:
override func viewDidAppear(animated: Bool) {
let backgroundMusicURL = NSBundle.mainBundle().URLForResource("tempMusic.mp3", withExtension: nil)
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: backgroundMusicURL, error:nil)
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay();
backgroundMusicPlayer.play();
}
This works as intended, but I am unable to control its volume in the scenes themselves.
So, is there a way to have background music playing so that it runs smoothly throughout multiple scenes and the volume is still adjustable from within these scenes?
回答1:
Okay I got it to work using the link presented by Matt (so future viewers of this post up vote his comment).
if let vc = UIApplication.sharedApplication().keyWindow?.rootViewController as? GameViewController{
vc.setMusicVolume(Float(hexData.musicVolume)/100.0);
}
I now access the rootViewController from within the scenes themselves. I put it inside an if statement just as a precaution.
回答2:
You should be able to access the viewController with:
self.view?.window?.rootViewController
That said, it is not recommended since it breaks the MVC pattern.
来源:https://stackoverflow.com/questions/28183914/using-avaudioplayer-across-multiple-scenes-swift-and-be-able-to-adjust-volume