使用 AVPlayer 在后台播放视频会出现 AspectFill 和循环问题

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

这是我所拥有的,我希望此视频充满整个屏幕 (aspectFill)

playerLayer.videoGravity = kCAGravityResizeAspectFill 应该进行纵横比填充,但屏幕顶部和底部仍然出现黑条。

最后一行本应循环播放视频,但它只是变暗并停止播放。

如有任何建议,我们将不胜感激。

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()
}

您使用的视频引力值有误,请更改为:

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

请注意,此值适用于视频,因为您使用的值用于重新缩放图像。

为了让您的视频循环播放,您刚刚忘记在播放完视频后倒带。我不使用 swift 但在 Objc C 中,您的 loopVideo 函数将如下所示:

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