Using AVAudioPlayer across multiple scenes Swift a

2019-07-20 07:54发布

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?

2条回答
狗以群分
2楼-- · 2019-07-20 08:03

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.

查看更多
够拽才男人
3楼-- · 2019-07-20 08:22

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.

查看更多
登录 后发表回答