2016-02-19 87 views
0

當回製作者我有一個遊戲,其包括3個視圖控制器:背景音樂重疊的viewController

  • 的viewController
  • settingViewController
  • GameViewController

我已經設置的背景音樂和在viewController類中播放它

var backgroundMusic : AVAudioPlayer! 
func setUpSounds(){ 
     //button sound 
     if let buttonSoundPath = NSBundle.mainBundle().pathForResource("buttonClick", ofType: "mp3") { 
      let buttonSoundURL = NSURL(fileURLWithPath: buttonSoundPath) 
      do { 
       try buttonSound = AVAudioPlayer(contentsOfURL: buttonSoundURL) 
      }catch { 
       print("could not setup button sound") 
      } 
      buttonSound.volume = 0.5 
     } 
     //background sound 
     if let backgroundMusicPath = NSBundle.mainBundle().pathForResource("BackgroundMusic", ofType: "mp3") { 
      let backgroundMusicURL = NSURL(fileURLWithPath: backgroundMusicPath) 
      do { 
       try backgroundMusic = AVAudioPlayer(contentsOfURL: backgroundMusicURL) 
      }catch { 
       print("could not setup background music") 
      } 
      backgroundMusic.volume = 0.2 
      /* 
      set any negative integer value to loop the sound 
      indefinitely until you call the stop method 
      */ 
      backgroundMusic.numberOfLoops = -1 
     } 
    } 


override func viewDidLoad() { 
     super.viewDidLoad() 
     self.setUpSounds() 
     self.playBackgroundSound() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

當我移動到settingViewController然後再回到viewController的聲音重放和重疊舊的播放音樂。

這個問題的解決方案是什麼?

回答

0

您必須先檢查AVAudioPlayer是否正在播放音樂,然後致電playBackgroundSound

您還可以將SoundManager作爲單件使用,以便從應用程序的其他部分操縱它。

class SoundManager{ 
     static var backgroundMusicSharedInstance = AVAudioPlayer? 
    } 

在查看

func setUpSounds(){ 
      //background sound 

     if SoundManager.backgroundMusicSharedInstance == nil { 
      if let backgroundMusicPath = NSBundle.mainBundle().pathForResource("BackgroundMusic", ofType: "mp3") { 
       let backgroundMusicURL = NSURL(fileURLWithPath: backgroundMusicPath) 
       do { 
        try SoundManager.backgroundMusicSharedInstance = AVAudioPlayer(contentsOfURL: backgroundMusicURL) 
       }catch { 
        print("could not setup background music") 
       } 
       SoundManager.backgroundMusicSharedInstance!.volume = 0.2 
       /* 
       set any negative integer value to loop the sound 
       indefinitely until you call the stop method 
       */ 
       SoundManager.backgroundMusicSharedInstance!.numberOfLoops = -1 
      } 
     } 
} 


    override func viewDidLoad() { 
      super.viewDidLoad() 
      self.setUpSounds() 
      if SoundManager.backgroundMusicSharedInstance!.playing == false{ 
        self.playBackgroundSound() 
       }  
    } 
+0

沒有幫助,還是同樣的問題。 –

+0

您使用的是模態或推塞格? – UlyssesR

+0

我已經使用故事板連接了它 –