当应用程序迅速进入背景时如何使用AVLayer继续以VideoView图层的形式播放视频

时间:2018-08-07 06:37:23

标签: ios swift avplayer ios-background-mode

我正在使用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 个答案:

答案 0 :(得分:0)

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

  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
}

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