iOS画中画

iOS 14 画中画

打开项目后台模式

WX20230516-091820_2x

创建视频播放源

let url = Bundle.main.url(forResource: "annie", withExtension: "mp4")!
avPlayerItem = AVPlayerItem(url: url)
avPlayer = AVPlayer(playerItem: avPlayerItem)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer?.frame = CGRectMake(0, 0, hgScreenW, hgScreenH - 200)
view.layer.addSublayer(avPlayerLayer!)

检查是否支持

AVPictureInPictureController.isPictureInPictureSupported()

导入 AVKit 创建 AVPictureInPictureController,并设置代理

import AVKit
if AVPictureInPictureController.isPictureInPictureSupported() {
            do {
                let session = AVAudioSession.sharedInstance()
                try session.setCategory(.playback)
                try session.setActive(true)
            } catch {}
            self.pipViewController = AVPictureInPictureController(playerLayer: self.avPlayerLayer!)
            self.pipViewController?.delegate = self
        }

代理方法包括

func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        print("画中画将要开始")
    }

    func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        print("画中画已经开始")
    }

    func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        print("画中画将要停止")
    }

    func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {
        print("画中画已经停止")
    }
    
    func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) {
        print("画中画开始失败:\(error.localizedDescription)")
    }
    
    func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
        print("恢复播放界面")
    }

开启画中画

手动开启和结束

self.avPlayer?.play()
if AVPictureInPictureController.isPictureInPictureSupported(){
    self.pipViewController?.startPictureInPicture()
    self.pipViewController?.stopPictureInPicture()
}

pictureInPictureControllerDidStopPictureInPicture 代理方法中可以处理关闭画中画后的视频

RPReplay_Final1684200828

非手动开启

点击播放的时候不手动开启,播放后返回桌面

RPReplay_Final1684201036

posted @ 2023-05-25 14:47  R1cardo  阅读(168)  评论(0编辑  收藏  举报