我正在创建一个音频应用程序,我希望音频能够继续在后台播放。(屏幕关闭)
在xcode上启用了后台模式,我实现了“AVAudioSession.sharedInstance”,但是在屏幕关闭后音频不会继续播放。有什么想法解决这个问题吗?
var player:AVAudioPlayer!
init(withStartingClosure block1:@escaping(_ dict:[String:Any],_ index:Int) -> Void,andStopingClosure block2:@escaping(_ index:Int) -> Void,finishedAllClosure block3:((_ finished:Bool) -> Void)? = nil) {
self.didStartPlaying = block1
self.didStopPlaying = block2
self.didFinishPlaying = block3
}
deinit {
self.mode = .stopped
}
}
extension AudioPlayer {
func getURL(ofAudio name:String) -> URL {
let url = URL(string: name)!
let nm = url.deletingPathExtension().absoluteString
let type = url.pathExtension
let path = Bundle.main.url(forResource: nm, withExtension: type)!
return path
}
func setupPlayer(withData data:[String:Any]){
let name = data["audio"] as! String
var idx = self.currentIndex - 1
if idx < -1 {
idx = -1
}
print("\nCurrentIndex = \(idx),and Audio is = \(data)")
let path = self.getURL(ofAudio: name)
do {
try self.setupAudioSession()
self.player = try AVAudioPlayer(contentsOf: path)
self.player.delegate = self
if self.player.prepareToPlay() == true {
self.player.play()
self.didStartPlaying?(data, idx)
}else{
print("----------Can't Play \(data)")
}
}
catch {
print(error.localizedDescription)
let alert = UIAlertView(title: "Error!", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
}
// func backgroundSession()
func backgroundSession() {
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
}
}
答案 0 :(得分:0)
您可以将其称为功能......
func backgroundSession() {
var audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch {
}
}
答案 1 :(得分:0)
确保在Info.plist中&#34; UIBackgroundModes&#34;密钥包括&#34;音频&#34;值。
此外,我建议按以下顺序使用AVAudioSession共享实例和AVAudioPlayer实例:
希望它有所帮助。