gpt4 book ai didi

swiftui - 循环 iOS14 VideoPlayer

转载 作者:行者123 更新时间:2023-12-05 04:57:28 24 4
gpt4 key购买 nike

我对 SwiftUI 还很陌生,我不太确定如何在 iOS 14 上使用 VideoPlayer 循环播放视频,而且我发现的相关文档很少。我发现的大多数解决方案在很多方面都非常复杂和令人困惑。如果有人能提供帮助,我将不胜感激。

VideoPlayerHelper.swift文件

import Foundation
import AVKit
//AutoPlay Video
var videoPlayer: AVPlayer?

func playVideo(fileName: String, fileFormat: String) -> AVPlayer {
if Bundle.main.url(forResource: fileName, withExtension: fileFormat) != nil {
videoPlayer = AVPlayer(url: Bundle.main.url(forResource: fileName, withExtension: fileFormat)!)
// videoPlayer?.play()

}
return videoPlayer!
}

VideoPlayerView.swift文件

import SwiftUI
import AVKit

struct VideoPlayerView: View {
// MARK: - PROPERTIES
var videoSelected: String
var videoTitle: String

// MARK: - BODY
var body: some View {
VStack {
VideoPlayer(player: playVideo(fileName: videoSelected, fileFormat: "mp4"))
} }

非常感谢!

最佳答案

基本上,您在 onAppear 上添加一个通知观察器,每次播放器结束时,您将时间设置为 0 并重新开始播放。

struct VideoPlayerView: View {
@State var player = AVPlayer(url: Bundle.main.url(forResource: "YourURL", withExtension: "mp4")!)
var body: some View {
VideoPlayer(player: player)
.frame(width: 400, height: 300, alignment: .center)
.onAppear {
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { _ in
player.seek(to: .zero)
player.play()
}
}

}
}

如果有帮助,请在正确答案上打勾

关于swiftui - 循环 iOS14 VideoPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64408704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com