Swift AVQueuePlayer 播放完视频

Swift AVQueuePlayer finished playing video

每次我的 AVQueuePlayer 播放完视频时,我都会尝试收到通知,但目前,这只能工作一次,之后就不会再收到通知。

func setupVideoPlayer(video: videos) {
    self.player.insert(AVPlayerItem(url: video), after: nil)
}

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
        NotificationCenter.default.removeObserver(notification.name)
    }
}

您将在调用观察者后将其移除!

NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
    print("VIDEO FINISHED")
    NotificationCenter.default.removeObserver(notification.name)
}

这里,

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
        NotificationCenter.default.removeObserver(notification.name)
    }
}

收到第一次通知后,您正在删除观察者,因此它不会第二次观察到相同的通知。

删除最后一行:

func handlePlayVideo() {
    player.play()
    print(player.currentItem)
    NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { (notification) in
        print("VIDEO FINISHED")
    }
}