AVPlayer 播放本地视频

guard let urlString = Bundle.main.path(forResource: "ad_video", ofType: "mp4") else {
            print("not found..")
            return
        }

        print(urlString);
        
        let assetVideo = AVURLAsset(url: URL(fileURLWithPath: urlString));
    
        playerItem = AVPlayerItem(asset: assetVideo) // 创建视频资源
        // 监听缓冲进度改变
        playerItem.addObserver(self, forKeyPath: LoadedTimeRanges, options: NSKeyValueObservingOptions.new, context: nil)
        // 监听状态改变
        playerItem.addObserver(self, forKeyPath: Status, options: NSKeyValueObservingOptions.new, context: nil)
        
        // 将视频资源赋值给视频播放对象
        avPlayer = AVPlayer(playerItem: playerItem)
        
        // 初始化视频显示layer
        playerLayer = AVPlayerLayer(player: avPlayer)
        // 设置显示模式
        playerLayer.videoGravity = .resizeAspectFill
        playerLayer.contentsScale = UIScreen.main.scale
    
        // 位置放在最底下
        self.layer.insertSublayer(playerLayer, at: 0)

你可能感兴趣的:(AVPlayer 播放本地视频)