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

标签 ios swift avfoundation background-music

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

    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")

最佳答案

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

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

当您的 Controller 检测到您的应用程序在后台运行时调用此函数:

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

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

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

然后调用这个函数:

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

希望对你有帮助;)

关于ios - 当应用程序在后台运行时(即按下主页按钮时)停止音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928618/

相关文章:

ios - 如何从屏幕上删除行?

ios - 使用 Swift 在没有 Storyboard的情况下展开 segue

ios - 如何在 UIView 中呈现 SFSafariViewController

swift - 如何在命令行工具中以 Apple 的 Swift 语言获取用户输入?

iphone - 使用 AVFoundation Framework(AVCaptureSession) 在 iPhone 中录制视频?

ios - getControlPointAtIndex 参数类型

iOS CommonCrypto 引用

android - 使用 Ionicframework 创建本地存储(设备,而非缓存)

ios - 使用 AVAudioSession 播放音频

ios - 如何在 iOS Swift 中更改音频的 BPM(每分钟节拍数)?