包装AVPlayer行为时处理AVPlayerLayer

问题描述 投票:1回答:1

我正在尝试将AVPlayer包装在我自己的类中,因此我可以提供一个更好的API来在我的整个应用程序中使用,这样我就可以模拟播放器的行为来测试其他对象(并且AVPlayer KVO非常难看使用!)。这是我尝试使用播放和暂停功能的简化模型:

protocol VideoPlayerProtocol {
    func play()
    func pause()
}

class AVPlayerWrapped: VideoPlayerProtocol {

    private let player = AVPlayer()

    init(playerItem: AVPlayerItem) {
        self.player.replaceCurrentItem(with: playerItem)
    }

    func play() {
        player.play()
    }

    func pause() {
        player.pause()
    }
}

我也有一个PlayerView,它将AVPlayerLayer添加到视图中。在Apple文档中,这是通过为视图提供AVPlayer

来设置的
class PlayerView: UIView {

    override class var layerClass: AnyClass {
        return AVPlayerLayer.self
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

    var player: AVPlayer? {
        get { playerLayer.player }
        set { playerLayer.player = newValue }
    }
}

[问题是,当我设置一个AVPlayerWrapped对象时,为了在视图中显示回放,我需要向AVPlayerplayer属性显示基础PlayerView,这使我无法包装播放器。

[我是否有办法以某种方式使用AVPlayerLayer而无需AVPlayerWrapped公开其底层参与者?还是我采用错误的方法?

非常感谢任何指导!

ios swift avfoundation avplayer
1个回答
0
投票
class AVPlayerWrapped: VideoPlayerProtocol {

    fileprivate let player = AVPlayer()

    init(playerItem: AVPlayerItem) {
        self.player.replaceCurrentItem(with: playerItem)
    }

    func play() {
        player.play()
    }

    func pause() {
        player.pause()
    }
}

extension AVPlayerLayer {
    func setPlayerWrapper(_ playerWrapped: AVPlayerWrapped) {
        player = playerWrapped.player
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.