how to play a video in UIView swift?

社会主义新天地 提交于 2019-12-21 11:39:31

问题


I have a video which I want to download from a server and stream it in a fixed view. I've set a UIView in my storyboard with fixed constraints, and here is what I've done in code:

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

And in my viewDidLoad I've done this:

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

My problem is my video is not with the size that I've set to videoView and in every device my video is in a different size. In some devices, the video height is larger than the height that I've set and it overlays the items that I have below videoView. How can I play video in a view in a right way?


回答1:


If you want to use 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()
}

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



回答2:


the only way to add a video to a UIView with fixed constraints in storyboard, was this :

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)

I hope other can use this! :)




回答3:


You can try to use AVPlayerLayer in a AVPlayer.

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


来源:https://stackoverflow.com/questions/50653779/how-to-play-a-video-in-uiview-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!