非常类似于这个问题:
Using AVAudioPlayer across multiple scenes Swift and be able to adjust volume
我想在多个场景中播放BGmusic,但是当我进入某些场景时我需要它停止。
例如,我的所有菜单场景都应该播放音乐,但是当我进入GamePlayScene时,当前的音乐应该停止并播放新的音乐。
我已经在上面的帖子中实现了修复,(根据我的需要稍微改了一下)但它不起作用...... 现在发生的事情是BGmusic继续播放,然后我的游戏音乐也播放
if let vc = UIApplication.sharedApplication().keyWindow?.rootViewController as? GameViewController{
vc.menuMusicPlayer.stop()
println("stop the bg audio")
}
这个println甚至没有被执行 - 暗示if
不是真的?
我的GameViewController是我所有场景的父亲......
不确定我在哪里错了。有什么建议?
GameViewController代码 - 里面
override func viewDidLoad {
var menuMusicPlayer:AVAudioPlayer = AVAudioPlayer()
var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("menuSounds", withExtension: "m4a")!
menuMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
menuMusicPlayer.volume = 0.25
menuMusicPlayer.numberOfLoops = -1
menuMusicPlayer.prepareToPlay()
if music_on == true && menuMusicPlayer.playing == false { menuMusicPlayer.play() }
我还有一个func来停止GameViewController中的音乐 我已经尝试触发func或只是直接告诉menuMusicPlayer stop()并且都没有工作。
func BGMusicStop() {
if menuMusicPlayer.playing == true {
menuMusicPlayer.stop()
println("bg music should stop")
}
}
答案 0 :(得分:0)
viewDidLoad中的代码仅将音频播放器分配给局部变量。在viewDidLoad完成后,您将无法获得对它的引用。避免重新声明menuMusicPlayer或至少在结尾处分配self.menuMusicPlayer。您需要在此处指定self,因为使用类变量和具有相同名称的局部变量会导致歧义。
至于为什么你不能从你想要的任何地方获得rootVC使用if if ...我怀疑你的rootVC是其他类(很难说你的意思是“是我所有场景的父母” ),但我建议不要使用你为音频播放器的所有权采取的方法。通过sharedApplication-> rootVC以及所有看似hacky的东西。也许您应该实现单例或服务定位器来包含要在整个应用程序中使用的实例。