我正在使用avplayer从远程服务器播放音频文件。当我播放此文件时,首先从URL播放avplayer流,然后播放文件。现在,我只想检测文件流传输何时完成并开始播放。
这是我的代码:
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
player = AVPlayer(url: down_url)
player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
player.volume = 1.0
player.play()
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" {
if player.rate > 0 {
print("player started")
}
}
}
我使用此代码进行检测,但是当avplayer开始流式传输时,它仅打印一次“播放器启动”。但是我无法检测到avplayer何时开始播放。
答案 0 :(得分:0)
为什么您不尝试下载文件然后在本地播放? 您可以使用Alamofire来处理下载,这样您就可以轻松知道下载完成的时间。
答案 1 :(得分:0)
注册为播放器项目的status属性的观察者
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &playerItemContext)
此方法将被调用
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
}
// Observer for Player status
if keyPath == #keyPath(AVPlayerItem.status) {
let status: AVPlayerItem.Status
if let statusNumber = change?[.newKey] as? NSNumber {
status = AVPlayerItem.Status(rawValue: statusNumber.intValue)!
} else {
status = .unknown
}
// Switch over status value
switch status {
case .readyToPlay:
// Player item is ready to play.
player.play()
playerControlsView.setPlayerControlsReady()
case .failed:
// Player item failed. See error.
print("Fail")
case .unknown:
// Player item is not yet ready.
print("unknown")
}
}
}
添加观察者以监视播放器何时播放
NotificationCenter.default.addObserver(self, selector:#selector(self.playerDidFinishPlaying(note:)),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
此方法将在玩家结束播放时调用
@objc func playerDidFinishPlaying(note: NSNotification){
print("Finished Playing")
}
完成播放器操作后,别忘了删除观察者
NotificationCenter.default.removeObserver(self)