iOS - 获取当前 AVPlayer(Item) 状态



我正在寻找一个明确的答案,如何在iOS 9上获取当前AVPlayer/AVPlayerItem状态。简单来说,让它们成为谷歌的ExoPlayer风格状态:

  • 空闲(无介质或错误(

  • 缓冲(视频实际上没有播放/前进和等待 更多数据(

  • 正在播放(视频实际上正在播放/前进(

  • 已完成(视频播放完毕(

请注意,在这一点上,我不是在寻找一种跟踪状态变化的方法(通过通知、KVO 观察或其他方式(,只是当前时间点的状态。请考虑以下伪代码:

typedef enum : NSUInteger {
PlayerStateIdle,
PlayerStateBuffering,
PlayerStatePlaying,
PlayerStateCompleted
} PlayerState;
+ (PlayerState)resolvePlayerState:(AVPlayer*)player {
// Magic code here
}

墙壁,到目前为止我一直在撞我的头:

  • timeControlStatus从 iOS 10 开始可用

  • playbackBufferEmpty永远是真的

  • playbackBufferFull总是假

  • 乍一看,loadedTimeRanges可能看起来很有希望,但既没有指示必须预先缓冲多少时间才能播放,也不能保证currentTime处于加载时间范围的边缘是一个停滞。

根据文档

您可以使用键值观察来观察这些状态变化,因为它们 发生。要观察的最重要的玩家物品属性之一是 它的地位。状态指示项目是否已准备好播放,并且 一般可供使用。

要设置观察:

func prepareToPlay() {
let url = <#Asset URL#>
// Create asset to be played
asset = AVAsset(url: url)
let assetKeys = [
"playable",
"hasProtectedContent"
]
// Create a new AVPlayerItem with the asset and an
// array of asset keys to be automatically loaded
playerItem = AVPlayerItem(asset: asset,
automaticallyLoadedAssetKeys: assetKeys)
// Register as an observer of the player item's status property
playerItem.addObserver(self,
forKeyPath: #keyPath(AVPlayerItem.status),
options: [.old, .new],
context: &playerItemContext)
// Associate the player item with the player
player = AVPlayer(playerItem: playerItem)
}

要处理:

override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
// Only handle observations for the playerItemContext
guard context == &playerItemContext else {
super.observeValue(forKeyPath: keyPath,
of: object,
change: change,
context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItemStatus
// Get the status change from the change dictionary
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over the status
switch status {
case .readyToPlay:
// Player item is ready to play.
case .failed:
// Player item failed. See error.
case .unknown:
// Player item is not yet ready.
}
}
}

不确定你的问题是什么。

您可以只访问 player.status 或 player.timeControlStatus 并返回与您的 ENUM 匹配的结果

。这是你的意思吗?

相关内容

最新更新