skip to Main Content

I am working on a component for a video that should essentially be played without controls, sound as well as autostart and loop. I got everything working via code below, besides looping bit, can’t seem to find any way to set this behavior on VideoPlayer nor AvPlayer. Would appreciate any pointers.

import SwiftUI
import AVKit


struct IntroductionVideo: View {  
  @State private var player = AVPlayer()
  
  // Body
  var body: some View {
      VideoPlayer(player: player)
        .aspectRatio(contentMode: .fit)
        .onAppear {
          player = AVPlayer(url: URL(string: "https://example.com/video.mp4")!)
          player.isMuted = true
          player.play()
        }
        .disabled(true)
  }
}

2

Answers


  1. You can observe the AVPlayerItem‘s .AVPlayerItemDidPlayToEndTime notification and seek the player back to the start when it reaches the end of the video.

    Just add this block before player.play():

    NotificationCenter
        .default
        .addObserver(
            forName: .AVPlayerItemDidPlayToEndTime,
            object: player.currentItem,
            queue: .main
        ) { _ in
            player.seek(to: .zero)
            player.play()
        }
    
    Login or Signup to reply.
  2. VideoPlayer isn’t relevant unless you are trying to add controls. You still have to use AVPlayerItem from the AVPlayer.

    .onReceive(NotificationCenter
        .default
        .publisher(
            for: .AVPlayerItemDidPlayToEndTime,
            object: player.currentItem),
               perform: { _ in
                    player.seek(to: .zero)
                    player.play()
                }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search