背景音乐在返回创建者视图控制器时重叠



我有一个由3个视图控制器组成的游戏:

  • 视图控制器
  • 设置视图控制器
  • 游戏视图控制器

我已经设置了背景音乐并在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.
    }

当我移动到设置视图控制器然后再次回到视图控制器时,声音会重播并重叠旧播放的音乐。

这个问题的解决方案是什么?

您必须在呼叫playBackgroundSound之前检查AVAudioPlayer是否正在播放音乐。

您还可以将 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()
              }    
    }

最新更新