Создайте переменную AVPlayer для вашего класса.
let player: AVPlayer = AVPlayer()
Затем создайте AVPlayerItem и установите его в player.
func prepareToPlayAudio() {
let url = newUrl
asset = AVAsset(url: url)
let assetKeys = ["playable", "hasProtectedContent"]
playerItem = AVPlayerItem(asset: asset,
automaticallyLoadedAssetKeys: assetKeys)
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext)
player = AVPlayer(playerItem: playerItem)
}
Затем добавьте наблюдателей для отслеживания состояния воспроизводимого элемента.
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &playerItemContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
switch status {
case .readyToPlay:
// Ready to play.
case .failed:
// Player item error.
case .unknown:
// Item is not ready.
}
}
}