AVPlayerLayer没有显示AVPlayer视频?

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];

当前视图的层次结构设置是否不当?


你的Bundle中是否包含视频商店? - user2924482
2个回答

14

你需要设置图层的frame属性。例如:

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

如果您尝试过这个方法,但在视图控制器的视图中无效,那么很可能是因为您试图将AVPlayerLayer的 frame 属性设置为视图控制器的 framebounds 属性,而该属性在创建 AVPlayerLayer 时为 {0, 0, 0, 0}。您需要在布局传递期间设置播放器的框架,此时视图控制器的 frame 将被设置为除 {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 代码。

这对我没有用;frame属性立即具有正确的值(而不是CGRectZero),但再次设置它并没有帮助。(iOS 14,真实设备)。 - hotdogsoup.nl

2

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

我们添加了这段代码,现在视频可以播放。不幸的是,AVPlayer没有内置控件,不像MPMoviePlayerController。不清楚为什么苹果正在弃用一个将具有非标准化视频播放选项的工具。

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];

8
对我没有用。在Storyboard中,我有一个专门的UIView包含了播放器层。我能够看到绿色的背景颜色,但是没有视频。 - ninjaneer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接