[英]Can't bind button to AVPlayer
I am trying to make a detailed view in swift, but I just can't figure out a way to pause the video with a custom button.我正在尝试在 swift 中进行详细查看,但我无法找到使用自定义按钮暂停视频的方法。 And also when I go back to my list I can still hear the video playing in the background.
而且当我 go 回到我的列表时,我仍然可以听到在后台播放的视频。 Here is my code for the AVPlayer and for the button.
这是我的 AVPlayer 和按钮的代码。
import SwiftUI
import AVKit
struct Workdetail: View {
var work: WorkoutDe
@State var player = AVPlayer()
@State var isplaying = true
var body: some View {
VStack {
ZStack {
VideoPlayer(player: $player, work: work)
.frame(height: UIScreen.main.bounds.height / 3.5)
Butto(player: $player, isplaying: $isplaying)
}
Spacer()
}
}
}
struct Butto : View {
@Binding var player : AVPlayer
@Binding var isplaying : Bool
var body : some View{
Button(action: {
if self.isplaying{
self.player.pause()
self.isplaying = false
}
else{
self.player.play()
self.isplaying = true
}
}) {
Image(systemName: self.isplaying ? "pause.fill" : "play.fill")
.font(.title)
.foregroundColor(.white)
.padding(20)
}
}
}
struct VideoPlayer : UIViewControllerRepresentable {
var work : WorkoutDe
@Binding var player : AVPlayer
var playerLayer = AVPlayerLayer()
public func makeUIViewController(context: Context) -> AVPlayerViewController {
let player = AVPlayer(url: URL(fileURLWithPath: String(work.url)))
let controller = AVPlayerViewController()
controller.player = player
controller.videoGravity = .resizeAspectFill
player.actionAtItemEnd = .none
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: player.currentItem, queue: .main) { _ in
player.seek(to: CMTime.zero)
player.play()
}
player.play()
return controller
}
func rewindVideo(notification: Notification) {
playerLayer.player?.seek(to: .zero)
}
public func updateUIViewController(_ uiViewController: AVPlayerViewController, context: UIViewControllerRepresentableContext<VideoPlayer>) {
}
}
The AVPlayer
works but when I press the button nothing happens. AVPlayer
可以工作,但是当我按下按钮时没有任何反应。 The image for the button changes but the video won't stop playing.按钮的图像发生变化,但视频不会停止播放。 Can someone please explain to me how I can bind the button, because I can't figure it out
有人可以向我解释如何绑定按钮,因为我无法弄清楚
Here is the code for a the problem, if you guys are looking for it.这是问题的代码,如果你们正在寻找它。 Someone answered it on another post:
有人在另一个帖子中回答:
public func makeUIViewController(context: Context) -> AVPlayerViewController {
let player = AVPlayer(url: URL(fileURLWithPath: String(work.url)))
let controller = AVPlayerViewController()
DispatchQueue.main.async {
self.player = player
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.