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

时间:2015-01-06 06:18:18

标签: 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 ... 
}

当用户在锁定屏幕上时,还需要添加什么来确保声音播放?

1 个答案:

答案 0 :(得分:5)

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

添加到ViewController:

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

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