1

我想以自定义大小显示 .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)


  }
4

1 回答 1

4

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

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()

    }

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

于 2017-06-30T12:21:03.807 回答