我不知道这段代码有什么问题。播放器项目似乎已加载,但视频无法播放。我只是有一个 swifui 内容视图,其中包含视频播放器和保存播放器的播放器控制器。控制器直接从应用程序结构馈入内容视图,并且加载方法从菜单栏项触发。我已经用多个视频尝试过这个方法。加载后播放器状态始终为“未知”,播放器错误为零。
class PlayerController: ObservableObject {
@Published var player: AVPlayer = AVPlayer()
func loadURL(url: URL) {
let newPlayerItem: AVPlayerItem = AVPlayerItem(url: url)
player.replaceCurrentItem(with: newPlayerItem)
player.play()
switch player.status {
case .unknown:
print("status unknown")
case .readyToPlay:
print("status ready to play")
case .failed:
print("status failed")
}
print(player.error?.localizedDescription)
}
}
struct ContentView: View {
@ObservedObject private var playerController: PlayerController
var body: some View {
VideoPlayer(player: playerController.player)
}
init(playerController: PlayerController) {
self.playerController = playerController
}
}
视频本应在从 url 加载时播放,但会显示错误屏幕。VideoPlayer 错误屏幕
使用原始代码尝试此方法并适当加载视频 在
.onAppear
中并删除您的 init(playerController: PlayerController)
,
如示例代码所示:
class PlayerController: ObservableObject {
@Published var player: AVPlayer = AVPlayer()
func loadURL(url: URL) {
let newPlayerItem: AVPlayerItem = AVPlayerItem(url: url)
player.replaceCurrentItem(with: newPlayerItem)
player.play()
switch player.status {
case .unknown:
print("status unknown")
case .readyToPlay:
print("status ready to play")
case .failed:
print("status failed")
}
print(player.error)
}
}
struct ContentView: View {
@ObservedObject var playerController: PlayerController
var body: some View {
VideoPlayer(player: playerController.player)
.onAppear {
let url = URL(string: "https://getsamplefiles.com/download/mp4/sample-1.mp4")!
playerController.loadURL(url: url)
}
}
}
@main
struct testApp: App {
@StateObject var playerController = PlayerController()
var body: some Scene {
WindowGroup {
ContentView(playerController: playerController)
}
}
}