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屋!