2015-04-12 65 views
1

非常類似於這樣的問題:在遊戲SWIFT AVAudioPlayer多個場景,停止不工作

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直接停止(),並沒有正在使用的音樂。

func BGMusicStop() { 
    if menuMusicPlayer.playing == true { 
     menuMusicPlayer.stop() 
    println("bg music should stop") 
    } 
} 

回答

0

您在viewDidLoad中的代碼只是將音頻播放器分配給本地變量。在viewDidLoad完成後,您將無法獲得對它的引用。避免重新聲明menuMusicPlayer或至少在最後分配self.menuMusicPlayer。由於使用類變量和具有相同名稱的本地變量導致的歧義,您需要在此處指定自己。

至於爲什麼你不能從任何地方得到rootVC使用你的if let ...那麼我懷疑你的rootVC是一些其他類(很難說你的意思是「是我的所有場景的父「),但我會建議您不要使用您爲音頻播放器所有權採取的方法。瀏覽共享應用程序 - > rootVC以及所有看起來很詭異的東西。也許你應該實現一個單例或者一個服務定位器來包含在你的應用程序中使用的實例。