无法使用自定义按钮暂停 AVPlayer
Posted
技术标签:
【中文标题】无法使用自定义按钮暂停 AVPlayer【英文标题】:Can't pause AVPlayer with custom button 【发布时间】:2020-06-22 15:31:21 【问题描述】:我正在尝试快速制作详细视图,但我无法找到使用自定义按钮暂停视频的方法。而且当我回到我的列表时,我仍然可以听到在后台播放的视频。这是我的 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
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>)
AVPlayer 可以工作,但是当我按下按钮时没有任何反应。按钮的图像发生变化,但视频不会停止播放。有人可以向我解释一下如何绑定按钮,因为我无法弄清楚
【问题讨论】:
【参考方案1】:您在子视图中与不同的玩家合作,尝试
public func makeUIViewController(context: Context) -> AVPlayerViewController
let player = AVPlayer(url: URL(fileURLWithPath: String(work.url)))
let controller = AVPlayerViewController()
DispatchQueue.main.async
self.player = player
绑定应该更新父状态,这将更新按钮,所以它应该工作。
【讨论】:
感谢您的帮助@Asperi。我可以看到现在“按钮”暂停了视频,但现在视频没有加载并显示“在视图更新期间修改状态,这将导致未定义的行为。”我还编辑了原始帖子。你能帮我提出解决这个问题的建议吗?以上是关于无法使用自定义按钮暂停 AVPlayer的主要内容,如果未能解决你的问题,请参考以下文章
html YouTube视频自定义暂停播放按钮,从给定时间开始