当 App 进入后台时停止 AVAudioPlayer

Stop the AVAudioPlayer when the App enters Background

当应用程序在我的 GameViewController 中不再处于活动状态时,我想停止无限背景音乐。我在 Objective-C 中找到了一种方法,但我在 Swift 中需要它。我尝试使用 viewDidUnload 但这根本不起作用。

这就是我实现 bgMusic 的方式。

var bgMusic:AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

var bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("bgMusic", withExtension: "wav")!
bgMusic = AVAudioPlayer(contentsOfURL: bgMusicURL, error: nil)
bgMusic.numberOfLoops = -1
bgMusic.prepareToPlay()
bgMusic.play()

}

简单的使用AppDelegate,这里有一个方法。

func applicationDidEnterBackground(application: UIApplication) {