Swiftui:设备锁定时保持视频播放器

发布于 2025-02-08 21:27:57 字数 485 浏览 3 评论 0原文

据我所知,标题说明了这一切。我有以下视图:

struct VideoView: View{
    @State var FilePath = ""
    @State private var player = AVPlayer()
    var body: some View{
        VideoPlayer(player: player)
            .onAppear{
                player = AVPlayer(url: URL(string: FilePath)!)
                player.play()
            }.onDisappear{
                player.pause()
            }
    }
}

我在ContentView中调用此视图,并且可以正常工作。但是,当我关闭应用程序或设备锁定时,视频会停止播放。有没有办法更改它以使其继续播放?

title says it all as far as I'm aware. I have the following view:

struct VideoView: View{
    @State var FilePath = ""
    @State private var player = AVPlayer()
    var body: some View{
        VideoPlayer(player: player)
            .onAppear{
                player = AVPlayer(url: URL(string: FilePath)!)
                player.play()
            }.onDisappear{
                player.pause()
            }
    }
}

I'm calling this in my ContentView, and it works fine. But when I close the app, or when the device is locked, the video stops playback. Is there a way that I can change this so that it will keep playing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乱世争霸 2025-02-15 21:27:57

花了一段时间才弄清楚,但我最终提出了以下解决方案。

  1. 确保您在图片中启用音频,播放和图片签名和能力
  2. 在定义avplayer时,添加以下代码:
player = AVPlayer(url: URL(string: FilePath)!)
do{
    try AVAudioSession.sharedInstance().setCategory(.playback)
    try AVAudioSession.sharedInstance().setActive(true)
}catch{
    print(error.localizedDescription)
}
player.audiovisualBackgroundPlaybackPolicy = .continuesIfPossible
  1. 您'重新完成,当您的设备被锁定或您在另一个应用程序中时,您的视频现在将播放。请注意,播放控件不会在模拟器上显示,但是在设备上工作正常。

It took a while to figure it out, but I eventually came up with the following solution.

  1. make sure that you enable Audio, AirPlay and Picture in Picture under Signing and Capabilities
  2. When you define your AVPlayer, add the following code:
player = AVPlayer(url: URL(string: FilePath)!)
do{
    try AVAudioSession.sharedInstance().setCategory(.playback)
    try AVAudioSession.sharedInstance().setActive(true)
}catch{
    print(error.localizedDescription)
}
player.audiovisualBackgroundPlaybackPolicy = .continuesIfPossible
  1. You're done, your video will now play when your device is locked or you are in another app. Note that playback controls do not show on the simulator, however it works fine on the device.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文