How to Loop Avplayer in Swift

Looping a video with AVFoundation AVPlayer?

You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification

When setting up the player:

ObjC

  avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[avPlayer currentItem]];

this will prevent the player to pause at the end.

in the notification:

- (void)playerItemDidReachEnd:(NSNotification *)notification {
AVPlayerItem *p = [notification object];
[p seekToTime:kCMTimeZero];
}

this will rewind the movie.

Don't forget un unregister the notification when releasing the player.

Swift

avPlayer?.actionAtItemEnd = .none

NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: .AVPlayerItemDidPlayToEndTime,
object: avPlayer?.currentItem)

@objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: kCMTimeZero)
}
}

Swift 4+

@objc func playerItemDidReachEnd(notification: Notification) {
if let playerItem = notification.object as? AVPlayerItem {
playerItem.seek(to: CMTime.zero, completionHandler: nil)
}
}

How to loop a video with AVPlayer (macOS)?

I found a solution just now. This might not be the best approach to this question. If anyone have better ideas, please post your answers and let's discuss together.

So, in this case, we can use NotificationCenter to add an observer to our AVPlayer object.

Here's the code.

struct AVPlayerViewRepresented: NSViewRepresentable {
var player: AVPlayer

func makeNSView(context: Context) -> some NSView {
let controller = AVPlayerView()
controller.player = player
controller.controlsStyle = .none
loopVideo(player: player)

return controller
}

func updateNSView(_ nsView: NSViewType, context: Context) {}

func loopVideo(player plr: AVPlayer) {
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: plr.currentItem, queue: nil) { notification in
plr.seek(to: .zero)
plr.play()
}
}
}

How can I make my video loop in swift with playerViewController?

The quickest way to do this is to use an AVQueuePlayer with an AVPlayerLooper. You can set the player on your player view controller the same as you would with an ordinary AVPlayer, but you need to keep a persistent reference around to the looper so it’ll keep working. In other words, add this to your view controller’s interface:

var looper: AVPlayerLooper?

…and in your viewDidAppear, replace this:

let player = AVPlayer(url: videoURL!)

with this:

let player = AVQueuePlayer()
looper = AVPlayerLooper(player: player, templateItem: AVPlayerItem(asset: AVAsset(url: videoURL!)))

Then, once you start the player playing, its video will loop indefinitely.



Related Topics



Leave a reply



Submit