如何在UIView swift中播放视频?

时间:2018-06-02 05:24:19

标签: ios swift avplayer

我有一个视频,我想从服务器下载并在固定视图中流式传输。 我在我的故事板中设置了一个带有固定约束的UIView,这就是我在代码中所做的:

@IBOutlet weak var videoView: UIView!
var player: AVPlayer!
var avpController = AVPlayerViewController()

viewDidLoad我已经完成了这个:

let url = URL(string:myURL)
player = AVPlayer(url: url!)

avpController.player = player
avpController.videoGravity = AVLayerVideoGravity.resizeAspect.rawValue
self.addChildViewController(avpController)
avpController.view.frame = videoView.frame
self.containerView.addSubview(avpController.view)
videoView.layer.masksToBounds = true

我的问题是我的视频不是我设置为videoView的尺寸,而且在每个设备中我的视频尺寸都不同。在某些设备中,视频高度大于我设置的高度,它覆盖了我videoView以下的项目。如何以正确的方式在视图中播放视频?

3 个答案:

答案 0 :(得分:4)

如果您想使用AVPlayerViewController:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
    playerViewController.player!.play()
}

对于AVPlayer:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()

答案 1 :(得分:4)

将视频添加到故事板中具有固定约束的UIView的唯一方法是:

let url = URL(string:myURL)

        player = AVPlayer(url: url!)

        avpController.player = player

        avpController.view.frame.size.height = videoView.frame.size.height

        avpController.view.frame.size.width = videoView.frame.size.width

        self.videoView.addSubview(avpController.view)

我希望其他人可以使用这个! :)

答案 2 :(得分:3)

您可以尝试在AVPlayerLayer中使用AVPlayer

      let player = AVPlayer(url: video) // your video url
      let playerLayer = AVPlayerLayer(player: player)
      playerLayer.frame = videoView.bounds
      videoView.layer.addSublayer(playerLayer)
      player.play()