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

Posted

技术标签:

【中文标题】当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放【英文标题】:How to continue play video as VideoView layer using AVLayer when app enters in background in swift 【发布时间】: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()
    

【问题讨论】:

【参考方案1】:

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

    您必须正确配置您的AVAudioSession 在后台运行时断开 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

有关更多信息,请查看这些文档:link1link2link3

【讨论】:

以上是关于当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放的主要内容,如果未能解决你的问题,请参考以下文章

快速 NSTimer 在后台

当应用程序进入后台模式时释放图形

当应用程序进入后台时如何停止可运行?

进入信标区域时如何在后台作为信标做广告

当 iphone 应用程序进入后台或前台状态时,如何保存数据?

当应用程序进入后台时,URLSessions 给 URLResponse nil