我将 SwiftUI 嵌入VideoPlayer
到 a 中VStack
,看到当设备旋转时屏幕变黑(即即使视频播放器自动旋转,内容也会消失)。即使我使用AVPlayerViewController
(as UIViewControllerRepresentable
),也会出现此问题。这是一个错误还是我做错了什么?
var videoURL:URL
let player = AVPlayer()
var body: some View {
VStack {
VideoPlayer(player: player)
.frame(maxWidth:.infinity)
.frame(height:300)
.padding()
.ignoresSafeArea()
.background {
Color.black
}
.onTapGesture {
player.rate = player.rate == 0.0 ? 1.0 : 0.0
}
Spacer()
}
.ignoresSafeArea()
.background(content: {
Color.black
})
.onAppear {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.duckOthers)
} catch {
NSLog("Unable to set session category to playback")
}
let playerItem = AVPlayerItem(url: videoURL)
player.replaceCurrentItem(with: playerItem)
}
}
通过像这样声明
let player = AVPlayer()
为属性View
,player
每次View
重新评估时都会重新创建。您应该将播放器存储在持久的地方(基于@State
或的@StateObject
解决方案)。