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

时间:2015-11-03 21:42:33

标签: ios swift video avplayer avkit

这里有我的内容,我希望这个视频能够填满整个屏幕(aspectFill)

playerLayer.videoGravity = kCAGravityResizeAspectFill 应该做Aspect Fill,但我仍然会在屏幕的顶部和底部出现黑条。

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

任何建议都表示赞赏。

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

1 个答案:

答案 0 :(得分:7)

您使用错误的视频重力值请更改为:

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

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

为了让你的视频循环播放,你刚刚忘记在完成播放后回放视频。我不使用swift但是在Objc C中你的loopVideo函数看起来像这样:

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