gpt4 book ai didi

ios - 当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放

转载 作者:行者123 更新时间:2023-11-30 11:16:12 48 4
gpt4 key购买 nike

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

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 与演示文稿的连接

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

    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
}

有关更多信息,请查看这些文档:
link1
link2
link3

关于ios - 当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51720318/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com