ios - Swift - 在锁定屏幕上,ios :AVPlayer在使用控件时播放多个音频实例

为了播放音轨(存储在服务器中),我建立了一个创建AVPlayerViewController实例的函数。


func playAudio(_ url: URL) {


 let avAssest = AVAsset(url: url)


 let playerItem = AVPlayerItem(asset: avAssest)



 audioPlayer = AVPlayer(playerItem: playerItem)



 let playerViewController = AVPlayerViewController()


 playerViewController.player = audioPlayer



 try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])



 self.present(playerViewController, animated: true, completion: {


 self.audioPlayer.play()



 })


}



播放器在前台工作时工作良好,如果我进入锁定屏幕,音频会继续播放,如果我按锁定屏幕中的暂停按钮,音频暂停,问题是,如果我在锁定屏幕上单击“播放”,则我正在收听的音频会恢复,但是从头开始播放第二个音频实例,所以现在我同时有两个音频实例播放,如果我再次暂停并再次按下播放键,则音频的另一个实例开始播放。

我正在使用Xcode 11 ,Swift 4.2开发

时间:

修改你的代码以看起来像这个(注意使它成为本地的更改):


 let avAssest = AVAsset(url: url)


 let playerItem = AVPlayerItem(asset: avAssest)



 let audioPlayer = AVPlayer(playerItem: playerItem) // *



 let playerViewController = AVPlayerViewController()


 playerViewController.player = audioPlayer



 try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])



 self.present(playerViewController, animated: true, completion: {


 audioPlayer.play() // *



 })



...