swiftui中的播放控件 [英] Playback controls in swiftui
问题描述
尝试使用AVKit的AVPlayer播放没有播放控件的视频:
Attempting to use AVKit's AVPlayer to play a video without playback controls:
private let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "videoToPlay", ofType: "mp4")!))
player.showsPlaybackControls = false
以上结果导致错误消息,声明必须用';'分隔.我也尝试过:
The above results in an error message that declarations must be separated by ';'. I've also tried:
VideoPlayer(player: player)
.onAppear {
player.showsPlaybackControls = false
}
这会导致其他错误.
关于使用swiftui隐藏播放控件的任何建议吗?
Any advice on hiding playback controls with swiftui?
推荐答案
VideoPlayer
似乎没有任何可在文档中找到的用于控制是否显示播放控件的方法.
VideoPlayer
does not appear to have any methods on it that I can find in the documentation to control whether the playback controls are shown.
showPlaybackControls
不起作用,因为 AVPlayer
也不具有该属性.
showPlaybackControls
doesn't work because AVPlayer
doesn't have that property either.
现在看来,您必须像包装 AVPlayerViewController
:
It looks like for now you'll have to do something like wrap an AVPlayerViewController
:
请注意,这是一个非常有限的示例,并未考虑您可能需要考虑的许多情况,例如由于父更改而重新加载 AVPlayerControllerRepresented
时会发生什么?是否需要使用 updateUIViewController
来更新其属性?您可能还需要比我使用的存储更稳定的解决方案来存储您的 AVPlayer
,并且在父视图发生更改时也将重新创建该解决方案.但是,所有这些都是相对容易解决的体系结构决策(请查看ObservableObject,StateObject,Equatable等)
Note that this is a very limited example and doesn't take into account a lot of scenarios you may need to consider, like what happens when AVPlayerControllerRepresented
gets reloaded because it's parent changes -- will you need to use updateUIViewController
to update its properties? You will also probably need a more stable solution to storing your AVPlayer
than what I used, which will also get recreated any time the parent view changes. But, all of these are relatively easily solved architectural decisions (look into ObservableObject, StateObject, Equatable, etc)
struct ContentView: View {
let player = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: "IMG_0226", ofType: "mp4")!))
var body: some View {
AVPlayerControllerRepresented(player: player)
.onAppear {
player.play()
}
}
}
struct AVPlayerControllerRepresented : UIViewControllerRepresentable {
var player : AVPlayer
func makeUIViewController(context: Context) -> AVPlayerViewController {
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
return controller
}
func updateUIViewController(_ uiViewController: AVPlayerViewController, context: Context) {
}
}
这篇关于swiftui中的播放控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!