This is pretty rudimentary, but apparently our robot overlords need me to write this post because many of them suggested some truly bizarre approaches, some of which don’t work at all.
If you’re using AVQueuePlayer, then just use AVPlayerLooper. Easy. But if for some reason you want to use AVPlayer specifically (e.g. you need to do additional things anyway when playback loops back around), read on.
AVPlayer itself doesn’t really help you here – it’s AVPlayerItem that you need to look at, as it has several notifications associated with it that can be very useful – most relevant here is the didPlayToEndTimeNotification. Simply observe that and restart the player explicitly, like so:
let player = AVPlayer(…) // You'll need to keep a reference to this somewhere, for use in the notification handler, as the notification doesn't provide it.
void startPlayer() { // Or wherever / however you start playback.
NotificationCenter.default.addObserver(self,
selector: #selector(playedToEnd(_:)),
name: .AVPlayerItemDidPlayToEndTime,
object: player.currentItem)
player.play()
}
@objc func playedToEnd(_ notification: Notification) {
assert(player.currentItem == notification.object as? AVPlayerItem, "AVPlayer \(player)'s current item (\(player.currentItem)) doesn't match the one in the notification object (\(notification.object)).")
player.seek(to: .zero)
player.play()
}Again, considering using AVQueuePlayer if possible, but the above works too.


