ani*_*teb 2 notifications ios avplayer swift avplayeritem
这是在我的代码中,从 url 播放的样子:
private func play() {
let streamUrl = ...
let playerItem = AVPlayerItem(url: streamURL)
radioPlayer = AVPlayer(playerItem: playerItem)
radioPlayer.volume = 1.0
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
UIApplication.shared.beginReceivingRemoteControlEvents()
} catch {
print("Error deactivating audio session.")
}
radioPlayer.play()
startListeningForStreamFail()
stopStartButton.setImage(#imageLiteral(resourceName: "pause_btn"), for: .normal)
}
Run Code Online (Sandbox Code Playgroud)
就像上面解释的代码片段一样,在调用该.play()函数后,我正在调用startListeningForStreamFail(),它将当前视图控制器注册到主线程上的两种类型的通知。
private func startListeningForStreamFail() {
DispatchQueue.main.async { [weak self] in
NotificationCenter.default.addObserver(self as Any, selector: #selector(self?.playerItemFailedToPlay), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: self?.radioPlayer?.currentItem)
NotificationCenter.default.addObserver(self as Any, selector: #selector(self?.playerItemFailedToPlay), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: self?.radioPlayer?.currentItem)
}
}
Run Code Online (Sandbox Code Playgroud)
选择器功能是这样的:
@objc private func playerItemFailedToPlay(notification: Notification) {
print("playerItemFailedToPlay")
}
Run Code Online (Sandbox Code Playgroud)
因为流现在工作正常,我试图通过在它的 url 中添加一些加号来测试失败。但是playerItemFailedToPlay()函数不会被调用,不会打印任何内容。
是否应该调用此选择器,即使仅更改了 url?
任何帮助,将不胜感激。谢谢!
我尝试在Github上构建一个项目以便于检查
我按照以下步骤操作:
将 NSAppTransportSecurity 添加到 info.plist如此答案中以允许 http
修剪提供的 url 以删除任何空格
let urlString = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
检查字符串是否提供有效链接
guard let url = URL(string: urlString) else { return complete(.unvalidURL) }
检查链接是否可以播放
AVAsset(url: url).isPlayable
如果前面的任何步骤不成功,则表示该 url 无效
在启动可玩链接后,我还为错误添加了一个观察者
NotificationCenter.default.addObserver(self, selector: #selector(itemFailedToPlayToEndTime(_:)), name: .AVPlayerItemFailedToPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(itemNewErrorLogEntry(_:)), name: .AVPlayerItemNewErrorLogEntry, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(itemPlaybackStalled(_:)), name: .AVPlayerItemPlaybackStalled, object: nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |