RoyRao
RoyRao

Reputation: 181

How to loop a video with AVPlayer (macOS)?

I'm currently using this in SwiftUI on macOS.
The reason why I'm wrapping this in NSViewRepresentable is that I don't need a playback control in my video. :)
My video plays perfectly but I wonder how can I play it repeatedly until I leave the current View?
Here's my code.

struct AVPlayerViewRepresented: NSViewRepresentable {
    var player: AVPlayer
    
    func makeNSView(context: Context) -> some NSView {
        let controller = AVPlayerView()
        controller.player = player
        controller.controlsStyle = .none
        return controller
    }
    
    func updateNSView(_ nsView: NSViewType, context: Context) {}
}
AVPlayerViewRepresented(player: myPlayer)
                        .frame(myFrame)
                        .disabled(true)
                        .onAppear {
                            myPlayer.isMuted = true
                            myPlayer.play()
                        }
                        .onDisappear {
                            myPlayer.pause()
                        }

Upvotes: 2

Views: 312

Answers (1)

RoyRao
RoyRao

Reputation: 181

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()
        }
    }
}

Upvotes: 3

Related Questions