将 AVPlayerLayer 添加到 UIViewController

Add AVPlayerLayer to UIViewController

是否可以在稍后显示在 UIView 中的 UIViewController 中显示 AVPlayerLayer

我正在尝试做的示例代码:

...
UIView *parentView = reinterpret_cast<UIView *>(window->winId());

AVPlayer *_player;
AVURLAsset *_asset;
AVPlayerItem *_playerItem;
AVPlayerLayer *m_playerLayer;
_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];

// works with AVPlayerViewController
// AVPlayerViewController *playerController = [[AVPlayerViewController alloc] init];
// playerController.player = _player;

UIViewController *viewController = [[UIViewController alloc] init];
[viewController.view.layer addSublayer:m_playerLayer];

viewController.view.frame = CGRectMake(this->x(), this->y(), this->width(), this->height());
[parentView addSubview:viewController.view];

[_player play];
...

如果我尝试将播放器添加到 AVPlayerViewController 然后显示它,它会起作用,但我只想使用 AVPlayerLayer,因为我不需要视频控件,因为我将单独实现该功能。

您可以将 AVPlayerViewController

一起使用
avController.showsPlaybackControls = false;

或者直接添加图层

_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
m_playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:m_playerLayer ]; 
[_player play];

我将 UIView 子类化并通过 SH_Khans 方法添加到 AVPlayerLayer

_player = [[AVPlayer alloc] init];
NSURL *baseURL = [[NSURL alloc] initWithString: @"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
_asset = [AVURLAsset assetWithURL:baseURL];
_playerItem = [AVPlayerItem playerItemWithAsset: _asset];
[_player replaceCurrentItemWithPlayerItem:_playerItem];
m_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
m_playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:m_playerLayer ]; 
[_player play];

然后按照您的意愿处理子类化的 UIView。但是有几件事,如果您调整 AVPlayerLayerUIView 的大小,您必须调整 AVPlayerLayer 的大小,因为系统不会自动执行此操作。 另外请记住在 AVPlayerLayerUIView 上剪裁到边界,否则它不会像您想要的那样匹配您的框架。