0

我正在使用 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()
    }
}
4

1 回答 1

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

于 2018-08-07T08:25:35.430 回答