I'm total newbie in coding and are trying to make a small app for my own. This is working as I want but I've no idea how to make the movie loop? Tried to look everywhere but to difficult for me.
//
// ContentView.swift
// VideoWallPaperV5
//
// Created by Me on 13/04/2022.
//
import SwiftUI
import AVKit
struct ContentView: View {
let player = AVPlayer(url: Bundle.main.url(forResource: "small_movie", withExtension: "mp4")!)
var body: some View {
ZStack {
VideoPlayer(player: player)
.scaledToFill()
.edgesIgnoringSafeArea(.all)
.onAppear {
player.play()
// player.isMuted = true
}
VStack{
Text("Airplay to kitchen")
.multilineTextAlignment(.leading)
.padding()
.background(Color.black.cornerRadius(10).opacity(0.6))
.position(x: 200, y: 100)
.font(Font.custom("Hill", size: 33))
.lineSpacing(15)
.foregroundColor(Color.white)
Spacer()
}
}
}
}
CodePudding user response:
AVPlayerLooper provides a simple interface to loop a single AVPlayerItem. You create a player looper by passing it a reference to your AVQueuePlayer which you create by passing a reference to your AVPlayer.
Check out Apples documentation:
CodePudding user response:
If you want to loop your videoItem you should probably use AVQueuePlayer and AVPlayerLooper as it is the most proper way for your task.
But if you insist on using only AVPlayer and its interface you need to subscribe to NSNotification.Name.AVPlayerItemDidPlayToEndTime
And handle this notification by seeking to position 0.0 and triggering playback with play()
kinda pseudocode would look like this:
NotificationCenter.default.addObserver(self,
selector: #selector(itemPlayToEndTime),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime)
private func itemPlayToEndTime() {
let time = CMTime(seconds: 0.0, preferredTimescale: 1)
self.player.seek(to: time) { [weak self] completed in
guard completed else { return }
self?.player.play()
}
but I strongly recommend you learn about using AVQueuePlayer.