我需要为
AVPlayer
实现错误处理。我使用 AVPlayer(url: audioUrl)
创建一个实例,其中 audioUrl
是远程 mp3 文件的 URL。
我订阅这样的通知:
func observeAudioTrack() {
guard let currentItem = player.currentItem else { return }
notificationCenter.addObserver(self, selector: #selector(playerDidFail), name: .AVPlayerItemFailedToPlayToEndTime, object: currentItem)
notificationCenter.addObserver(self, selector: #selector(playerDidLogError), name: .AVPlayerItemNewErrorLogEntry, object: currentItem)
}
但是,当我测试关闭互联网连接或使用无效 URL 时,这些方法都不会被调用。
player.status
是 readyToPlay
,player.error
是 nil
。
我成功接收了
AVPlayerItemNewErrorLogEntry
,但仅限于流(m3u8
格式)。
PS。我使用装有 iOS 15.0 的 iPhone 12 Pro 进行测试。
NSNotification.Name.AVPlayerItemNewErrorLogEntry 从 iOS 6.0 开始已弃用。请改用 AVPlayerItem.newErrorLogEntryNotification。这个对我有用。同样的事情可能适用于 NSNotification.Name.AVPlayerItemDidPlayToEndTime 但我还没有测试过。请改用 AVPlayerItem.failedToPlayToEndTimeNotification。
仅供代码阅读器使用的代码:
func observeAudioTrack() {
guard let currentItem = player.currentItem else { return }
notificationCenter.addObserver(self, selector: #selector(playerDidFail), name: AVPlayerItem.failedToPlayToEndTimeNotification, object: currentItem)
notificationCenter.addObserver(self, selector: #selector(playerDidLogError), name: AVPlayerItem.newErrorLogEntryNotification, object: currentItem)
}
我在AVFoundation中找到了信息:
@available(macOS, introduced: 10.7, deprecated: 100000, message: "Use AVPlayerItem.failedToPlayToEndTimeNotification instead.")
@available(iOS, introduced: 4.3, deprecated: 100000, message: "Use AVPlayerItem.failedToPlayToEndTimeNotification instead.")
@available(tvOS, introduced: 9.0, deprecated: 100000, message: "Use AVPlayerItem.failedToPlayToEndTimeNotification instead.")
@available(watchOS, introduced: 1.0, deprecated: 100000, message: "Use AVPlayerItem.failedToPlayToEndTimeNotification instead.")
public static var AVPlayerItemFailedToPlayToEndTime: NSNotification.Name { get }
和
@available(macOS, introduced: 10.9, deprecated: 100000, message: "Use AVPlayerItem.newErrorLogEntryNotification instead.")
@available(iOS, introduced: 6.0, deprecated: 100000, message: "Use AVPlayerItem.newErrorLogEntryNotification instead.")
@available(tvOS, introduced: 9.0, deprecated: 100000, message: "Use AVPlayerItem.newErrorLogEntryNotification instead.")
@available(watchOS, introduced: 1.0, deprecated: 100000, message: "Use AVPlayerItem.newErrorLogEntryNotification instead.")
public static var AVPlayerItemNewErrorLogEntry: NSNotification.Name { get }
尝试这样注册 NotificationCenter.default.addObserver(self, 选择器: #selector(finishedPlaying), 名称:NSNotification.Name.AVPlayerItemDidPlayToEndTime,对象:playerItem)