Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing a video in the background with AVPlayer giving problems with AspectFill and looping

Here's what I have and I want this video to fill the whole screen (aspectFill)

playerLayer.videoGravity = kCAGravityResizeAspectFill is supposed to do the Aspect Fill but I still get black bars at the top and bottom of the screen.

The last line is supposed to loop the video but instead it just dims and stops playing.

Any suggestions are appreciated.

var moviePlayer: AVPlayer!

override func viewDidLoad() {
    super.viewDidLoad()    

    // Load the video from the app bundle.
    let videoURL: NSURL = NSBundle.mainBundle().URLForResource("video", withExtension: "mp4")!

    self.moviePlayer = AVPlayer(URL: videoURL)
    self.moviePlayer.muted = true

    let playerLayer = AVPlayerLayer(player: self.moviePlayer)
    playerLayer.videoGravity = kCAGravityResizeAspectFill //this not working
    playerLayer.zPosition = -1

    playerLayer.frame = self.view.frame

    self.view.layer.addSublayer(playerLayer)

    self.moviePlayer.play()

    // Loop video.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "loopVideo", name: AVPlayerItemDidPlayToEndTimeNotification, object: self.moviePlayer)
}

func loopVideo() {
    self.moviePlayer.play()
}
like image 319
Harout360 Avatar asked Mar 14 '23 06:03

Harout360


1 Answers

You are using the wrong value for video gravity please change to:

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

Note that this value is for videos where as the value you used is used for rescaling images.

And for getting your video to loop you have just forgotten to rewind the video after it has finished playing. I don't use swift but in Objc C your loopVideo function would look like this:

-(void) loopVideo {
    [self.moviePlayer seekToTime:kCMTimeZero];
    [self.moviePlayer play];
}
like image 193
Rory O'Logan Avatar answered Apr 26 '23 07:04

Rory O'Logan