如何在解雇后停止将 AVPlayerViewController 作为 UIViewRepresentable 播放? [英] How to stop playback of AVPlayerViewController as UIViewRepresentable after dismissal?
问题描述
我创建了一个 UIViewRepresentable 版本的 AVPlayerViewController 来使用 SwiftUI 播放电影,提供一个 URL 和可选的启用/禁用控件.这是代码:
I have created a UIViewRepresentable version of AVPlayerViewController to play movies using SwiftUI, with a provided URL and optionally enabling/disabling controls. Here is that code:
struct PlayerViewController: UIViewRepresentable {
// Provide the player to this swiftui view
var url: URL
var showControls: Bool = true
typealias UIViewType = UIView
func makeUIView(context: UIViewRepresentableContext<PlayerViewController>) -> UIView {
let controller = AVPlayerViewController()
controller.player = AVPlayer(url: url)
controller.showsPlaybackControls = showControls
context.coordinator.controller = controller
return controller.view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PlayerViewController>) {
}
func makeCoordinator() -> PlayerViewController.Coordinator {
Coordinator()
}
class Coordinator: NSObject {
var controller: AVPlayerViewController?
deinit {
print("deinit coordinator")
}
}
}
播放器是详细视图的一部分,可从嵌入在 NavigationView 中的列表访问,如下所示:
The player is part of a detail view that is access from a List embedded in a NavigationView, like this:
NavigationView {
List {
NavigationLink(destination: DetailView(url: URL("url to movie")))
}
}
DetailView
简单地使用提供的 url 实例化 PlayerViewController
.
DetailView
simply instantiates PlayerViewController
with the provided url.
我遇到的问题是,如果我在 DetailView
中播放电影,当我点击后退按钮从 DetailView
返回到主屏幕时,我可以仍然可以听到电影中的音频很明显仍在屏幕外播放.
The problem I'm having is that if I play the movie in DetailView
, when I hit the back button to return from DetailView
to the main screen, I can still hear the audio from the movieit's clearly still playing off-screen.
其他 SO 问题表明这是因为在取消视图后保留了对 AVPlayer
的引用.如果是真的,我不知道为什么;或者,我似乎无法控制.
Other SO questions have indicated that this is because a reference to the AVPlayer
is kept after the view is dismissed. If true, I'm not sure why; or, it doesn't seem like I have control over that.
如果在返回主视图并听到后台播放的视频后,我点击另一个列表项,播放会立即停止,并且我会看到deinit coordinator"调试消息.
If, after returning to the main view and hearing the video playing in the background, I then tap another list item, the playback immediately stops and I see the "deinit coordinator" debug message.
当 PlayerViewController 被关闭并且用户返回主视图时,如何停止播放?
How can I stop playback when the PlayerViewController is dismissed and the user returns to the main view?
推荐答案
可以通过viewWillDisappear
方法添加扩展来暂停播放
You can pause playback through the viewWillDisappear
method by adding an extension
extension AVPlayerViewController {
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.player?.pause()
print("*** Video paused.")
}
}
这篇关于如何在解雇后停止将 AVPlayerViewController 作为 UIViewRepresentable 播放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!