how to play a video in UIView swift?
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()
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()
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! :)
This is how you can add and remove player in uiview.
var player: AVPlayer?
var playerController: AVPlayerViewController?
func removePlayer() {
player?.pause()
player = nil
playerController?.player?.pause()
playerController?.player = nil
if let view = playerController?.view {
videoView.willRemoveSubview(view)
}
playerController?.view.removeFromSuperview()
playerController = nil
}
func setVideo(url: URL) {
removePlayer()
player = AVPlayer(url: url)
playerController = AVPlayerViewController()
playerController?.player = player
self.videoView.addSubview((playerController?.view)!)
playerController?.view.frame = CGRect(x: 0, y: 0, width: self.videoView.bounds.width, height: self.videoView.bounds.height)
// player.play()
}