当应用程序在swift中进入后台时,如何使用AVLayer作为VideoView层继续播放视频



我正在使用AVPLayer在videoView中播放视频,但当应用程序进入后台模式并再次打开应用程序时,视频将暂停。

func playVideo() {
if let filePath = Bundle.main.path(forResource: "Audios/copy1", ofType:"mp4") {
let filePathUrl = NSURL.fileURL(withPath: filePath)
videoPlayer = AVPlayer(url: filePathUrl)
let playerLayer = AVPlayerLayer(player: videoPlayer)
playerLayer.frame = self.videoView.bounds
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer?.currentItem, queue: nil) { (_) in
self.videoPlayer?.seek(to: kCMTimeZero)
self.videoPlayer?.play()
self.videoPlayer.rate = 0.5
self.videoPlayer.actionAtItemEnd = .none
}
self.videoView.layer.addSublayer(playerLayer)
videoPlayer?.play()
}
}

是的,这是可能的,但您必须正确设置。

  1. 您必须正确配置AVAudioSession
  2. 进入后台时,断开AVPlayer与演示文稿的连接

对于第一点,您必须将音频背景模式设置为打开并配置音频会话:

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let _ = try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
print("an error occurred when audio session category.n (error)")
}

第二:

func applicationDidEnterBackground(_ application: UIApplication) {
// Disconnect the AVPlayer from the presentation when entering background
// If presenting video with AVPlayerViewController
playerViewController.player = nil
// If presenting video with AVPlayerLayer
playerLayer.player = nil
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Reconnect the AVPlayer to the presentation when returning to foreground
// If presenting video with AVPlayerViewController
playerViewController.player = player
// If presenting video with AVPlayerLayer
playerLayer.player = player
}

有关详细信息,请查看这些文档:
链接1
link2
链接3

相关内容

  • 没有找到相关文章

最新更新