繁体   English   中英

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

[英]Stop Music When App is running in background (i.e. when home button is pressed)

嗨,我用 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")

您可以像这样在控制器中使用观察者:

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()
}

希望对你有帮助 ;)

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

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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM