应用程序在后台运行时停止音乐(即按下主页按钮时)

时间:2016-03-10 22:28:14

标签: ios swift avfoundation background-music

嗨,我用swift构建一个基本游戏,有背景音乐。游戏有多个图像视图。我用下面的代码播放音乐。如果用户使用主页按钮退出应用程序,我该如何停止音乐。现在,即使用户按下主页按钮,音乐也会继续播放。背景音乐继续贯穿所有图像视图,这就是我想要的。

    func playBackgroundMusic(thesong: String) {
        let url = NSBundle.mainBundle().URLForResource(thesong, withExtension: nil)
        guard let newURL = url else {
            print("Could not find file: \(thesong)")
            return
        }
        do {
            backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
            backgroundMusicPlayer.numberOfLoops = -1
            backgroundMusicPlayer.prepareToPlay()
            backgroundMusicPlayer.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

    playBackgroundMusic("thesong.mp3")

2 个答案:

答案 0 :(得分:1)

您必须在控制器中使用此功能:

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

    backgroundMusicPlayer.pause()
}

答案 1 :(得分:1)

您可以在控制器中使用观察者,如下所示:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pauseSong:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)

当您的控制器检测到您的应用何时在后台运行时调用此函数:

func pauseSong(notification : NSNotification) {
    backgroundMusicPlayer.pause()
}

然后,当您的应用再次打开时,添加另一个观察者来播放歌曲:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("playSong:"), name:UIApplicationWillEnterForegroundNotification, object: nil)

然后调用此函数:

func playSong(notification : NSNotification) {
    backgroundMusicPlayer.play()
}

希望它可以帮到你;)

相关问题