在 Swift 3 中创建具有自定义大小的 VideoPlayer

Create VideoPlayer With Custom Size in Swift 3

我想以自定义大小显示 .mov 文件。我的控制器有一个 xib 文件。

顶视图是 UIView 的子类。我想在此视图中显示视频。 有我创建视频视图的代码。但是我的视频播放器的大小有问题。如何解决这个问题。

这是我的代码:

 private func playVideo() {
    guard let path = Bundle.main.path(forResource: "video_2017-06-30_15-49-05", ofType:"mov") else {
      debugPrint("video.m4v not found")
      return
    }
    let player = AVPlayer(url: URL(fileURLWithPath: path))
    let playerController = AVPlayerViewController()
    playerController.player = player

    let avPlayerLayer = AVPlayerLayer(player: player)
    avPlayerLayer.frame = videoView.layer.frame
    videoView.layer.insertSublayer(avPlayerLayer, at: 0)


  }

如果您希望使用搜索栏和播放暂停按钮将本地播放器添加到您的视图中,请使用以下代码:

private func playVideo() {
        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType:"mp4") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        playerController.view.frame = videoView.bounds
        videoView.addSubview(playerController.view)
        player.play()
    }

如果您只想使用 AVPlayerLayer 在您的视图中播放视频,那么您可以执行如下操作:

    var player : AVPlayer!
    var avPlayerLayer : AVPlayerLayer!
    @IBOutlet weak var videoView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()


        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType:"mp4") else {
            debugPrint("video.m4v not found")
            return
        }
        player = AVPlayer(url: URL(fileURLWithPath: path))
        avPlayerLayer = AVPlayerLayer(player: player)
        avPlayerLayer.videoGravity = AVLayerVideoGravity.resize

        videoView.layer.addSublayer(avPlayerLayer)
        playVideo()


    }

    override func viewDidLayoutSubviews() {

        avPlayerLayer.frame = videoView.layer.bounds
    }

    private func playVideo() {
        player.play()

    }

这对我来说很完美,希望对你有用:)