【问题标题】:Stop Music When App is running in background (i.e. when home button is pressed)当应用程序在后台运行时停止音乐(即按下主页按钮时)
【发布时间】:2016-06-26 00:19:20
【问题描述】:

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

【问题讨论】:

    标签: ios swift avfoundation background-music


    【解决方案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()
    }
    

    希望对你有帮助;)

    【讨论】:

    • 嘿 Tomas,谢谢你,当应用程序进入后台时,它会完美地停止音乐。再次打开应用程序时恢复音乐有点麻烦。音乐应该恢复吗?
    • UIApplicationWillEnterForegroundNotification添加另一个观察者并继续播放音乐
    • 你说得对,当你的应用再次打开时,你必须(重新)播放这首歌。让我看看
    【解决方案2】:

    你必须在你的控制器中使用这个函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多