Playing videos in the background using AVPlayer giving problems with AspectFill and loop

That's what I have, and I want this video to fill the entire screen (aspectFill)

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

The last line should loop the video, but instead it just dims and stops playing.

Any suggestions are welcome.

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()
}
+4
source share
1 answer

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

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

, , , .

, , . swift, Objc C loopVideo :

-(void) loopVideo {
    [self.moviePlayer seekToTime:kCMTimeZero];
    [self.moviePlayer play];
}
+7

Source: https://habr.com/ru/post/1614353/


All Articles