swift - AVFoundation 在后台/在 Swift 的锁定屏幕上播放音频

标签 swift ios8 avfoundation

我正在尝试使用 AVFoundation 找到一种方法,以便在用户处于锁定屏幕时或者他们在使用我的应用程序的过程中锁定应用程序时播放音频

class ViewController: UIViewController, AVAudioPlayerDelegate {
    var avPlayer: AVAudioPlayer?
    var error: NSError?

... other stuff ... 

    func playChime(fileName: String) -> Void {
        let fileURL: NSURL! = NSBundle.mainBundle().URLForResource(fileName, withExtension: "wav")
        self.avPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
        self.avPlayer?.play()
    }
... other stuff ... 
}

需要添加什么以确保当用户处于锁定屏幕时也能播放声音?

最佳答案

要在设备锁定时或在主屏幕上(在 Xcode 6.3 上)继续在后台播放音频:

添加到您的 ViewController:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

然后在您的 Info.plist 中,为 UIBackgroundModes 添加一个新条目并将其设置为音频。 Xcode 会自动将其填写为“需要后台模式”和“应用使用 Airplay 播放音频或流式传输音频/视频”

关于swift - AVFoundation 在后台/在 Swift 的锁定屏幕上播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27793138/

相关文章:

ios - AppDelegate 在我添加 firebase 时出错

ios-simulator - iOS8 中存储的用户默认 plist 文件在哪里?

ios - 为什么我的弹出窗口在 iPhone 6 Plus 上的 iOS 8.1 中崩溃? iOS 8 可以工作(实际上是 Xcode 6.0 到 6.1 的 bug)

ios - iOS 键盘的最大高度是多少?

ios/iphone 照片连拍模式 api

ios - 通过导航 Controller 取消 View 后应用程序崩溃?

ios - 根据外部点击来缩小 View ,而不使用手势识别器

swift - 运行框架内编写的 UITest

php - 来自 json 对象的快速 PUT API

ios - AVCaptureTorchModeAuto 不会持续更新手电筒模式