检测文件流已完成,可以使用avplayer播放



我正在用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是什么时候开始玩的。

注册为玩家物品状态属性的观察员

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)

相关内容

最新更新