6

让 AVPlayer 视频内容出现在一个人的视野中的诀窍是什么?

我们正在使用以下 AVPlayer 代码,但屏幕上没有出现任何内容。我们知道视频在那里,因为我们能够使用 MPMoviePlayerController 显示它。

这是我们正在使用的代码:

AVAsset *asset = [AVAsset assetWithURL:videoTempURL];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item];
player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:player];
// layer.frame = self.view.frame;
[self.view.layer addSublayer:layer];
layer.backgroundColor = [UIColor clearColor].CGColor;
//layer.backgroundColor = [UIColor greenColor].CGColor;
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[player play];

我们是否为当前视图设置了不正确的图层?

4

2 回答 2

14

您需要设置图层的框架属性。例如:

 self.playerLayer.frame = CGRectMake(0, 0, 100, 100)

如果您尝试了这个并且它在视图控制器的视图中不起作用,则很可能您尝试将图层的frame属性设置为视图控制器frame或创建时的bounds属性。您需要在布局过程中设置播放器的框架,此时视图控制器将设置为. 要正确执行此操作:{0, 0, 0, 0}AVPlayerLayerframe{0, 0, 0, 0}

如果您在自定义 UIView(包括 IB)中使用自动布局:

override func layoutSubviews() {
    super.layoutSubviews()

    //Match size of view
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    self.playerLayer.frame = self.bounds
    CATransaction.commit()
}

如果您在自定义 UIViewController 中使用自动布局:

override fun viewDidLayoutSubviews() {
  //Match size of view-controller
  CATransaction.begin()
  CATransaction.setDisableActions(true)
  self.playerLayer.frame = self.view.bounds
  CATransaction.commit()
}

这些CATransaction行用于禁用图层帧更改的隐式动画。如果您想知道为什么通常不需要这样做,那是因为默认情况下支持 UIView 的图层不会隐式动画。在这种情况下,我们使用的是非视图支持层 ( AVPlayerLayer)

最好的方法是通过界面构建​​向视图控制器添加一个新视图,并在新添加的视图上设置一个自定义类。然后创建该自定义视图类并实现layoutSubviews代码。

于 2015-12-17T01:15:28.437 回答
3

事实证明,AVPlayer 需要自己的上下文视图才能播放。

我们添加了这段代码,现在视频播放了。不幸的是,AVPlayer 没有与 MPMoviePlayerController 不同的内置控件。目前尚不清楚为什么 Apple 不赞成使用具有非标准化视频播放选项的工具。

UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0, 320.0f, 200.0f)];
layer.frame = self.view.frame;
[containerView.layer addSublayer:layer];
[self.view addSubview:containerView];
layer.backgroundColor = [UIColor greenColor].CGColor;
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[player play];
于 2015-07-14T09:57:46.843 回答