Проверьте, можно ли воспроизвести url, используя AVAsset(url: URL).isPlayable
, в вашем случае, прежде чем вы сможете играть
if avAsset.isPlayable {
playerItem = AVPlayerItem(asset: avAsset)
...
}
Для лучшего подхода используйте наблюдателей
class ViewController: UIViewController {
private var observerContext = 0
private let player = AVPlayer()
private var readyForPlayback = false
private var playerItem: AVPlayerItem? {
willSet {
playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &observerContext)
}
didSet {
playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.initial, .new], context: &observerContext)
}
}
private var asset: AVAsset? {
willSet {
readyForPlayback = false
asset?.removeObserver(self, forKeyPath: #keyPath(AVURLAsset.isPlayable), context: &observerContext)
}
didSet {
guard asset == nil else {
asset!.addObserver(self, forKeyPath: #keyPath(AVURLAsset.isPlayable), options: [.initial, .new], context: &observerContext)
return
}
playerItem = nil
player.replaceCurrentItem(with: nil)
}
}
// MARK: KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &observerContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
guard let keyPath = keyPath else { return }
switch keyPath {
case #keyPath(AVURLAsset.isPlayable):
guard asset?.isPlayable == true else { return }
playerItem = AVPlayerItem(asset: asset!)
player.replaceCurrentItem(with: playerItem)
case #keyPath(AVPlayerItem.status):
guard let status = playerItem?.status else { return }
if status == .readyToPlay {
guard !readyForPlayback else { return }
readyForPlayback = true
player.play()
} else if status == .failed {
readyForPlayback = false
if let error = playerItem?.error {
print("Error: \(error)")
}
}
default:
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
Использование
self.asset = AVAsset
При остановке воспроизведения
self.asset = nil