I’ve not too long ago began touching swiftUI. For iOS16, I wish to use AVFoundation to play the video for transition as soon as after which loop the video for loop, however I do not know a great way to do it.
I would love to have the ability to select to play the transition video with or with out the loop video.
I requested ChatGPT3.0 and it returned the code under, however this didn’t work: after the video for transition and the video for loop performs as soon as every, nothing is displayed.
I feel it’s beneath NotificationCenter
that’s not working, however I do not know learn how to change it.
import UIKit
import AVFoundation
class LoopingPlayerUIView: UIView {
non-public let playerLayer = AVPlayerLayer()
non-public var playerLooper: AVPlayerLooper?
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been carried out")
}
/// Relying in your video you may choose a correct `videoGravity` property to suit higher
init(loopedVideoName: String,
firstVideoName: String? = nil,
participant: AVQueuePlayer,
videoGravity: AVLayerVideoGravity = .resizeAspectFill) {
tremendous.init(body: .zero)
// Load the looped video
guard let loopedFileUrl = Bundle.primary.url(forResource: loopedVideoName, withExtension: "mp4") else { return }
let loopedAsset = AVAsset(url: loopedFileUrl)
let loopedItem = AVPlayerItem(asset: loopedAsset)
// Arrange the participant with the looped video
participant.isMuted = true
playerLayer.participant = participant
playerLayer.videoGravity = videoGravity
layer.addSublayer(playerLayer)
// Play the primary video as soon as if supplied
if let firstVideoName = firstVideoName {
guard let firstFileUrl = Bundle.primary.url(forResource: firstVideoName, withExtension: "mp4") else { return }
let firstAsset = AVAsset(url: firstFileUrl)
let firstItem = AVPlayerItem(asset: firstAsset)
playerLooper = AVPlayerLooper(participant: participant, templateItem: firstItem)
// Observer for the tip of the primary video
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { _ in
// Change to looped video and allow looping
self.participant.replaceCurrentItem(with: loopedItem)
self.playerLooper = AVPlayerLooper(participant: self.participant, templateItem: loopedItem)
self.participant.play()
}
} else {
// If firstVideoName will not be supplied, arrange the looper for the looped video instantly
playerLooper = AVPlayerLooper(participant: participant, templateItem: loopedItem)
}
}
override func layoutSubviews() {
tremendous.layoutSubviews()
playerLayer.body = bounds
}
}