我在我的项目中使用
AVPlayer
来播放视频流。我的项目是用 Swift 语言编写的。
如何检测
AVPlayer
中播放了错误的链接?
我用的是这个:
player.addObserver(self, forKeyPath: "status", options:NSKeyValueObservingOptions(), context: nil)
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (keyPath == "status") {
let status: AVPlayerStatus = self.playerViewController.player!.status
switch (status) {
case AVPlayerStatus.ReadyToPlay:
print("---------- ReadyToPlay ----------")
break
case AVPlayerStatus.Unknown, AVPlayerStatus.Failed:
print("---------- FAILED ----------")
break
}
}
}
但结果是它总是返回:
---------- ReadyToPlay ----------
任何提示都会有帮助。谢谢。
我已经检查过了。
您可以为您的播放器添加此功能。
player.addObserver(self, forKeyPath: "timeControlStatus", options:[.new, .old], context:nil)
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.status), options:[.new, .old], context:nil)
override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "timeControlStatus", let change = change, let newValue = change[NSKeyValueChangeKey.newKey] as? Int, let oldValue = change[NSKeyValueChangeKey.oldKey] as? Int {
let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldValue)
let newStatus = AVPlayer.TimeControlStatus(rawValue: newValue)
if newStatus != oldStatus {
DispatchQueue.main.async {
if newStatus == .playing || newStatus == .paused {
//playing
} else {
//loading video
}
}
}
}
if keyPath == #keyPath(AVPlayer.currentItem.status) {
let newStatus: AVPlayerItem.Status
if let newStatusAsNumber = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
newStatus = AVPlayerItem.Status(rawValue: newStatusAsNumber.intValue)!
} else {
newStatus = .unknown
}
if newStatus == .failed {
// this is just error you want to handle
print("Error: \(String(describing: self.player?.currentItem?.error?.localizedDescription)), error: \(String(describing: self.player?.currentItem?.error))")
}
}
}
希望这对你有帮助。
嗯,我还没有测试过,但试试这个。
player?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "status") {
let status: AVPlayerStatus = self.player!.status
if(status == AVPlayerStatus.readyToPlay){
print("Ready to play")
}
else{
if( status == AVPlayerStatus.unknown){
print("failed")
}
}
}
}
您还可以尝试使用 Joint Publisher 的不同方法来代替
addObserver
方法。
查看这个示例(在 SwiftUI 中):