17

I am putting n avplayer inside of a view controller to customize some other elements of the view controller but I still want the playback and scrubbing controls used in AVPlayerViewController. Is there a way to enable these controls for the Avplayer when I am not using AvPlayerViewcontroller?

Stefan
  • 5,203
  • 8
  • 27
  • 51
tnek316
  • 630
  • 1
  • 5
  • 16
  • 1
    Hey, did you get the solution. I am adding AVPlayerViewController as child view controller and kept its frame custom. But the controls like play, pause, scrubbing controls etc are not visible. Please help. – Ruchi Mar 24 '17 at 09:02

3 Answers3

34

No. The usual solution (explicitly advised by Apple) is to use the AVPlayerViewController as an embedded view controller - i.e., make your view controller a custom parent view controller and the AVPlayerViewController its child, and now you can place its view (the movie and the controls) inside your view as a subview in good order. Example (self is your view controller):

let url = // whatever
let player = AVPlayer(URL:url)
let avPlayerViewController = AVPlayerViewController()
avPlayerViewController.player = player
avPlayerViewController.view.frame = // whatever
self.addChild(avPlayerViewController)
self.view.addSubview(avPlayerViewController.view)
avPlayerViewController.didMove(toParent: self)
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • While this works great, Xcode will show errors like below:Unable to simultaneously satisfy constraints. It seems like the issue is with the autolayout of playback controls within AVPlayerViewController. Do think this is a bug though. – JSNoob Apr 20 '16 at 18:46
  • 1
    cant create the avplayerviewcontroller object in swift 3.0 – Ravi Ojha May 25 '17 at 06:30
  • 2
    @Natto The Ask Question button is big, blue, and at the top right. – matt Apr 25 '22 at 14:46
1

To update this post with Swift 5 you can try this code:

let videoURL = URL(string: "https://your_video_in_internet.mp4")
let player = AVPlayer(url: videoUrl)
let playerViewController: AVPlayerViewController!
playerViewController = AVPlayerViewController()
playerViewController.view.frame = YOUR_FRAME_OR_EMBED_IN_STORYBOARD
playerViewController.player = player
playerViewController.showsPlaybackControls = true
playerViewController.videoGravity = .resizeAspectFill
YOUR_FRAME_OR_EMBED_IN_STORYBOARD.addSubview(playerViewController.view)
playerViewController.player!.play()  
Diego Jiménez
  • 1,398
  • 1
  • 15
  • 26
0
let player = AVPlayer(url: url)    
let playerViewController = AVPlayerViewController()
playerViewController.view.frame = self.videoPlayerView.bounds
playerViewController.player = player
self.addChild(playerViewController)
self.videoPlayerView.addSubview(playerViewController.view)
playerViewController.didMove(toParent: self)
Syed Haris
  • 21
  • 3