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
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()
:VideoPlayer
isn’t relevant unless you are trying to add controls. You still have to useAVPlayerItem
from theAVPlayer
.