【问题标题】:How to continue play video as VideoView layer using AVLayer when app enters in background in swift当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放
【发布时间】:2018-08-07 06:37:23
【问题描述】:

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

【问题讨论】:

    标签: ios swift avplayer ios-background-mode


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多