Avplayer AVPlayerItemDidPlayToEndTime 通知未向观察者发送消息

Fap*_*ola 2 nsnotification ios avplayer swift

我正在使用AVQueuePlayer播放远程音频文件列表。我想默认实现重复所有。

我的方法是,我正在观察AVPlayerItemDidPlayToEndTime通知,并在播放完毕后将 playerItem 添加到队列的后面。

nextAudio(notification: Notification)不运行在所有。需要这方面的帮助,或者更好的方式来实现无限游戏。

func playAudio(_ items: [AVPlayerItem]) {

    let avPlayerVC = AVPlayerViewController()
    let player = AVQueuePlayer(items: items)
    player.actionAtItemEnd = .pause
    avPlayerVC.player = player

    for item in items {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(FilesViewController.nextAudio(notification:)),
                                               name: .AVPlayerItemDidPlayToEndTime, object: item)
    }

    present(avPlayerVC, animated: true) {
        self.player.play()
    }
}

@objc func nextAudio(notification: Notification) {
    debugPrint("nextAudio was called")
    guard player != nil else { return }
    debugPrint("AVPlayerItemDidPlayToEndTime notif info  \(notification.userInfo)")
    if let currentItem = notification.userInfo!["object"] as? AVPlayerItem {
        currentItem.seek(to: kCMTimeZero)
        self.player.advanceToNextItem()
        self.player.insert(currentItem, after: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*asz 5

我相信你已经明白了,但我只是遇到了自己,并决定回答:

当您指定通知对象时,它看起来似乎没有传递(顺便说一句,这应该是一种正确的方式)。可能是iOS中的一个错误...

你需要通过nil

NotificationCenter.default.addObserver(self, selector: #selector(videoDidPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)
Run Code Online (Sandbox Code Playgroud)

然后在方法中,您应该检查通知的对象是您的播放器项目。文档实际上并不一致,因为 Apple 声明通知的对象是 aAVplayer但它是 a AVPlayerItem

@objc
    private func videoDidPlayToEnd(_ notification: Notification) {
        guard let playerItem = notification.object as? AVPlayerItem, let urlAsset = playerItem.asset as? AVURLAsset else { return }
    gpLog("Sender urlAsset: \(urlAsset.url.absoluteString)")
        // Compare an asset URL.
    }
Run Code Online (Sandbox Code Playgroud)