Using AVAudioPlayer across multiple scenes Swift and be able to adjust volume

自作多情 提交于 2020-01-04 17:59:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!