简体   繁体   中英

Set size for Video with AVPlayerViewController

I need to play a short video at the end of my game.

I created an AVPlayerViewController on my storyboard with a modal presentation using a segue from the previous View Controller.

However I want the video NOT to cover the whole screen. Let's say 50% (centered) of the screen size.

Here is the code I tried :

import AVKit
import AVFoundation
import UIKit

class VideoPlayerViewController: AVPlayerViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidAppear(animated: Bool) {
    // Play video
    player?.play()
}

override func viewDidLayoutSubviews() {
    print(videoBounds)
    self.view.bounds = videoBounds
}

}

The problem is that the video scales to the whole screen is very small (like something around 100*70px). I believe the default size is 100*100 at some point and it scales it to match my video ratio.

If I don't specify bounds, it scales to the whole screen (video gravity don't let me the choice).

If I reduce the size on my whole view in viewDidLayoutSubviews, it's still not okay because this method is called multiple times so I keep changing my view bounds.

I can't believe how hard it is to display a local video on part of the screen with AVPlayerViewController...

Any help ?

You can make the view controller any size you'd like. Like this, if you wanted to:

let videoURL = URL(fileURLWithPath: videoPath)
let player = AVPlayer(url: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.view.frame = CGRect (x:100, y:100, width:200, height:100)
playerViewController.player = player  

self.addChildViewController(playerViewController)
self.view.addSubview(playerViewController.view)
playerViewController.didMove(toParentViewController: self)

(obviously, the above size would be weird, but you can. if you want to).

Use the ViewController if you want automatically managed player controls. If you want to roll your own controls, the layer is probably better.

Just posting this to correct the answer that indicated you shouldn't use the VC except in full screen. Seems to work fine for me.

AVPlayerViewController is only meant to be used in a full screen manner, you are better off using AVPlayerLayer this allows you to size / place it in a view of your choosing.

let player = AVPlayer(url: myURL)
let layer = AVPlayerLayer(player: player)
layer.frame.size = CGSize(100,100)
layer.frame.origin = myView.center

player.play()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM