I am trying to play a video inside a UIView, but the video player always appears outside of the UIView which I am embedding the AVPlayerViewController into.
Below is what I have so far....
class ViewController: UIViewController {
let smallVideoPlayerViewController = AVPlayerViewController()
#IBOutlet weak var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let myFileManager = FileManager.default
let mainBundle = Bundle.main
let resourcesPath = mainBundle.resourcePath!
guard let allItemsInTheBundle = try? myFileManager.contentsOfDirectory(atPath: resourcesPath) else {
return
}
let videoName = "test"
let videoPath = Bundle.main.path(forResource: videoName, ofType: "mp4")
let videoUrl = URL(fileURLWithPath: videoPath!)
smallVideoPlayerViewController.showsPlaybackControls = false
smallVideoPlayerViewController.player = AVPlayer(url: videoUrl)
videoView.addSubview(smallVideoPlayerViewController.view)
smallVideoPlayerViewController.view.frame = videoView.frame
smallVideoPlayerViewController.player?.play()
}
...
}
The background colour of UIView is set to white. As seen from the screenshot, AVPlayer is outside of the UIView.
I tried manually setting the dimensions and position of the AVPlayer, but no luck with that either.
I am using Xcode 9.2. The project has not warnings regarding to any layout issues.
How can I perfectly align the AVPlayer, so that is would appear inside the UIView.
Thanks
Change this line:
smallVideoPlayerViewController.view.frame = videoView.frame
to this:
smallVideoPlayerViewController.view.frame = videoView.bounds
The reason is because videoView.frame includes the origin in its superview which you don't want. videoView.bounds is just the size with an origin of 0,0.
Of course you might want to go further set the auto-resizing mask to keep the video player frame the same like this:
smallVideoPlayerViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
or even to go full blown auto-layout.
Related
I am building a screen where users can play audio files using an AVPlayerViewController. The problem is that I can't get rid of the QuickTime logo in the player view, see screenshot:
My code:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
guard let url = URL(string: filePath!) else {
return
}
let player = AVPlayer(url: url)
let controller = AVPlayerViewController()
controller.modalPresentationStyle = .overFullScreen
controller.player = player
self.present(controller, animated: true) {
player.play()
}
} catch {
}
I've tried adding an UIImageView using controller.contentOverlayView?.addSubView(), but I can't center that properly. How do I customize the layout of the player without having to build my own interface from scratch?
What you tried is correct: just add a subview to the content overlay view. But you left out one step: you must give both the subview and the content overlay view constraints, to make them cover the player controller’s view completely.
Example (my av is your controller):
let iv = UIView()
iv.backgroundColor = .white
av.contentOverlayView!.addSubview(iv)
let v = av.contentOverlayView!
iv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
iv.bottomAnchor.constraint(equalTo:v.bottomAnchor),
iv.topAnchor.constraint(equalTo:v.topAnchor),
iv.leadingAnchor.constraint(equalTo:v.leadingAnchor),
iv.trailingAnchor.constraint(equalTo:v.trailingAnchor),
])
NSLayoutConstraint.activate([
v.bottomAnchor.constraint(equalTo:av.view.bottomAnchor),
v.topAnchor.constraint(equalTo:av.view.topAnchor),
v.leadingAnchor.constraint(equalTo:av.view.leadingAnchor),
v.trailingAnchor.constraint(equalTo:av.view.trailingAnchor),
])
If all you want to do is remove the "Q" logo without replacing it with anything, you can get rid of this way:
(avPlayerViewController?.view.subviews.first?.subviews.first as? UIImageView)?.image = nil
But, at least for me, the "Q" logo usually only appears about 2 seconds after I've set up the player view controller. So you might need to use a timer to get the above code to run about 2 seconds after creating the player.
I am trying to add a sublayer of the function setupPlayerView below subviews which have been loaded previously. The subviews are loaded faster than the layer as the function creating the layer uses a string which is modified from another class, a UIViewController (I want to load individual videos). I found an answer on stackoverflow but the suggested solution of .insertSublayer(playerLayer, below: self.controlsContainerView.layer) did not work for me. How can I ensure the videolayer is under all my other subviews like controlsContainerView and its subviews (e.g. activityIndicatorView) in turn?
Here is what I got right now:
class PlayerView: UIView {
var urlString: String? {
didSet {
setupPlayerView()
}
}
override init(frame: CGRect){
super.init(frame: frame)
//although the function is called immediately it is not the "lower" than everything else
setupPlayerView()
//add subview with controls (e.g. spinner)
controlsContainerView.frame = frame
addSubview(controlsContainerView)
//add to subview and center spinner in subview
controlsContainerView.addSubview(activityIndicatorView) // (spinner)
controlsContainerView.addSubview(whiteView)
//...
}
//... irrelevant code (closures like `activityIndicatorView` and `whiteView`)
//setup video player
func setupPlayerView() {
if let urlString = self.urlString, let videoURL = NSURL(string: urlString){
print(urlString)
//player's video
if self.player == nil {
player = AVPlayer(url: videoURL as URL)
}
//add sub-layer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.frame
self.controlsContainerView.layer.insertSublayer(playerLayer, below: self.controlsContainerView.layer)
//when are frames actually rendered (when is video loaded so one can remove spinner)
player?.addObserver(self, forKeyPath: "currentItem.loadedTimeRanges", options: .new, context: nil)
}
}
For those interested: I change urlString the following way in another class (a ViewController):
videoPlayerView.urlString = videoUrl //videoUrl being some link to a video source
I am working on an iOS app using Swift 3 where I have a video playing in the background. My code was working completely fine until randomly the error message:
Type AVLayerVideoGravity aka (NSString) has no member resizeAspectFill
appears. I can't figure out at all why resizeAspectFill is no longer being recognized. Is there something I'm missing? I've tried cleaning my project but that does not fix anything. Any help would be greatly appreciated :)
Below is the code:
import Foundation
import AVFoundation
import UIKit
class HomeViewController: UIViewController {
// MARK: Properties
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
var enterButton: UIButton! = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Welcome"
let theURL = Bundle.main.url(forResource:"hannah", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = .none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = .clear
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd(notification:)),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
From the documentation of AVPlayerLayer (unfortunately the link redirects to the Swift 4 version. To see the changes enable Show API changes at top right).
The video gravity determines how the video content is scaled or
stretched within the player layer’s bounds. The player layer supports
the following video gravity values:
AVLayerVideoGravityResizeAspect
AVLayerVideoGravityResizeAspectFill
AVLayerVideoGravityResize
The default value is AVLayerVideoGravityResizeAspect.
The enum case you are referring to belongs to Swift 4
You need to say:
avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill .rawValue
I have a video view set to full screen. However while playing in the simulator, it is not running full screen.
This issue is only for iPads and not iPhones.
Here is my code:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
let bundle: Bundle = Bundle.main
let videoPlayer: String = bundle.path(forResource: "normalnewer", ofType: "mp4")!
let movieUrl : NSURL = NSURL.fileURL(withPath: videoPlayer) as NSURL
// var fileURL = NSURL(fileURLWithPath: "/Users/Mantas/Desktop/123/123/video-1453562323.mp4.mp4")
playerView = AVPlayer(url: movieUrl as URL)
NotificationCenter.default.addObserver(self,selector: #selector(playerItemDidReachEnd),name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: self.playerView.currentItem) // Add observer
var playerLayer=AVPlayerLayer(player: playerView)
// self.avPlayerLayer.playerLayer = AVLayerVideoGravityResizeAspectFill
playerLayer.frame = viewVideo.bounds
// self.playerLayer.frame = self.videoPreviewLayer.bounds
viewVideo.layer.addSublayer(playerLayer)
playerView.play()
UserDefaults.standard.set("normalnewer", forKey: "video")
}
I have tried checking landscape mode in target's general.
Gone through the threads below:
how to play a video in fullscreen mode using swift ios?
Play video fullscreen in landscape mode, when my entire application is in lock in portrait mode
Setting device orientation in Swift iOS
But these did not resolve my issue.
Here is a screenshot.
Can somebody help me resolve this?
I see you solved your issue, but I noticed you were using an AVPlayerLayer. The orientation rotation is handled with the AVPlayerViewController, but not with a custom view using a player layer. It is useful to be able to put the layer in fullscreen without rotating the device. I answered this question elsewhere, but I will put it here as well.
Transforms and frame manipulation can solve this issue:
extension CGAffineTransform {
static let ninetyDegreeRotation = CGAffineTransform(rotationAngle: CGFloat(M_PI / 2))
}
extension AVPlayerLayer {
var fullScreenAnimationDuration: TimeInterval {
return 0.15
}
func minimizeToFrame(_ frame: CGRect) {
UIView.animate(withDuration: fullScreenAnimationDuration) {
self.setAffineTransform(.identity)
self.frame = frame
}
}
func goFullscreen() {
UIView.animate(withDuration: fullScreenAnimationDuration) {
self.setAffineTransform(.ninetyDegreeRotation)
self.frame = UIScreen.main.bounds
}
}
}
Setting the frame of the AVPlayerLayer changes it's parent's frame. Save the original frame in your view subclass, to minimize the AVPLayerLayer back to where it was. This allows for autolayout.
IMPORTANT - This only works if the player is in the center of your view subclass.
Incomplete example:
class AVPlayerView: UIView {
fileprivate var avPlayerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
fileprivate var hasGoneFullScreen = false
fileprivate var isPlaying = false
fileprivate var originalFrame = CGRect.zero
func togglePlayback() {
if !hasGoneFullScreen {
originalFrame = frame
hasGoneFullScreen = true
}
isPlaying = !isPlaying
if isPlaying {
avPlayerLayer.goFullscreen()
avPlayerLayer.player?.play()
} else {
avPlayerLayer.player?.pause()
avPlayerLayer.minimizeToFrame(originalFrame)
}
}
}
After spending some time taking a good look at the Storyboard, I tried changing the fill to Aspect fill & fit and that resolved the problem :)
The best thing you can do is put this code
In viewDidLayoutSubviews and enjoy it!
DispatchQueue.main.async {
self.playerLayer?.frame = self.videoPlayerView.bounds
}
Currently I am having a dialogue view with four controls at the bottom. Each control is loading a different view inside the dialogue. One of these controls is setting an AVPlayer inside the dialogue view and is playing it. Unfortunately the AVPlayer itself comes without playback controls.
The AVPlayerViewController how ever does have playback controls. Is it possible to place a AVPlayerViewController inside a UIView so that it does not get started as a new screen? I would like to place it inside my UIView so that everything is taking place inside my dialgoue.
You can initialize the AVPlayerViewController and add it as a child to your ViewController , and insert it as a subview.
[self addChildViewController:yourPlayerViewController];
[self.view addSubview:yourPlayerViewController.view];
[yourPlayerViewController didMoveToParentViewController:self];
And to remove it:
[yourPlayerViewController willMoveToParentViewController:nil];
[yourPlayerViewController.view removeFromSuperview];
[yourPlayerViewController removeFromParentViewController];
EDIT SWIFT METHOD:
Check here for Swift
I'm using Swift 3.2 / Xcode 9.2 / iOS 11
This is how to do it in 9 easy steps. The steps are explained above each line
**Make sure you import AVKit to have access to the AVPlayerViewController or you won't be able to use it
// 1. to have access to the AVPlayerViewController import AVKit
import AVKit
// 2. create your class properties
var videoUrl: URL?
var player: AVPlayer?
let avPVC = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
// 3. make sure the url your using isn't nil
guard let videoUrl = self.videoUrl else { return }
// 4. init an AVPlayer object with the url then set the class property player with the AVPlayer object
self.player = AVPlayer(url: videoUrl)
// 5. set the class property player to the AVPlayerViewController's player
avPVC.player = self.player
// 6. set the the parent vc's bounds to the AVPlayerViewController's frame
avPVC.view.frame = self.view.bounds
// 7. the parent vc has a method on it: addChildViewController() that takes the child you want to add to it (in this case the AVPlayerViewController) as an argument
self.addChildViewController(avPVC)
// 8. add the AVPlayerViewController's view as a subview to the parent vc
self.view.addSubview(avPVC.view)
// 9. on AVPlayerViewController call didMove(toParentViewController:) and pass the parent vc as an argument to move it inside parent
avPVC.didMove(toParentViewController: self)
}
SWIFT 4 - Subview Method
The initial method works alright, but I feel like the view controller method seems messy when I really just want a subview. So, most of the time I play the video in a custom view (rather than using the entire AVPlayerViewController).
I use this method to show the video in a subview which completely fills an existing view. In the example below, urlToVideo is the URL to the video that you want to play, and existingView is the view we want to place our new view into (as a subview).
First, create a VideoPlayerView class in a new VideoPlayerView.swift file, with this, which is directly copy/paste from Apple's website, except that I called it VideoPlayerView rather than PlayerView.
import Foundation
import UIKit
import AVFoundation
/// A simple `UIView` subclass that is backed by an `AVPlayerLayer` layer.
class VideoPlayerView: UIView {
var player: AVPlayer? {
get {
return playerLayer.player
}
set {
playerLayer.player = newValue
}
}
var playerLayer: AVPlayerLayer {
return layer as! AVPlayerLayer
}
override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
}
Then, when I want to play the video, I create the subview and play it:
let player = AVPlayer(url: urlToVideo)
let playerFrame = CGRect(x: 0, y: 0, width: existingView.frame.width, height: existingView.frame.height)
let videoPlayerView = VideoPlayerView(frame: playerFrame)
videoPlayerView.player = player
existingView.addSubview(videoPlayerView)
player.play()
My solution is to have your view like a canvas and basically draw the AVPlayerViewController on top of it:
#IBOutlet weak var layerVideoView: UIImageView!
guard let url = Bundle.main.path(forResource: "santana", ofType: "mp4") else { return debugPrint("video not found") }
let path = URL(fileURLWithPath: url)
let player = AVPlayer(url: path)
let playerController = AVPlayerViewController()
playerController.player = player
playerController.view.frame = CGRect(x: layerVideoView.frame.origin.x, y: layerVideoView.frame.origin.y, width: layerVideoView.frame.width, height: layerVideoView.frame.height)
self.addChild(playerController)
self.view.addSubview(playerController.view)
LayerVideoView is an image view, but you can use just a UIView if that suits.
Its is important to add constraints in the Storyboard to your View because your Video Player will mimic the shape of your View.