我正在开发一个播放音频文件或流的应用程序,遇到了我无法解决的问题。本质上,当前项目发生故障后,我的AVPlayer不再播放新项目。下面是一个快速的应用程序,您可以复制/粘贴以进行复制。
import UIKit
import AVFoundation
class ViewController: UIViewController {
@objc var player: AVPlayer!
override func viewDidLoad() {
super.viewDidLoad()
self.player = AVPlayer.init(playerItem: AVPlayerItem.init(url: URL.init(string: "file:///Users/bobsacamano/Library/Developer/CoreSimulator/Devices/AD4CC461-847E-441B-98BA-D5A62EE210AE/data/Containers/Data/Application/F3AEA610-5358-4EAD-93B3-F30E9491D052/Library/07E2837C-5FF2-4B30-99A7-CCE683C19C29.mp3")!))
self.player.play()
self.addObserver(self, forKeyPath: #keyPath(player.currentItem.status), options: .new, context: nil)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(player.currentItem.status) {
switch player.currentItem!.status {
case .readyToPlay:
print("Ready to play")
case .failed:
print("Failure \(String(describing: player.currentItem!.error?.localizedDescription))")
self.player.replaceCurrentItem(with: AVPlayerItem.init(url: URL.init(string: "http://traffic.libsyn.com/atpfm/atp281.mp3")!))
self.player.play()
case .unknown:
print("Unknown")
}
}
}
}
初始AVPlayerItem不存在,因此KVO将返回失败。如果我尝试用有效的URL替换该项目,则仍然无法播放。我缺少明显的东西吗?
答案 0 :(得分:1)
https://developer.apple.com/documentation/avfoundation/avplayer/1388096-status文档说:“当此属性的值为AVPlayer.Status.failed时,您将无法再使用播放器进行播放,而需要创建一个新实例来替换它。” >