我正在尝试使用 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/