背景:有一个详情页面,页面的上半部分需要播放一段mp4视频。
流程:进入页面先将播放器渲染好,请求网络得到mp4地址自动播放。
网上查找相关资料需要用AVFoundation库的中的三个类:
1、AVPlayerItem
2、AVPlayer
3、AVPlayerLayer
DetailHeaderView.h代码
#import "BaseView.h"
#import <AVFoundation/AVFoundation.h>
NS_ASSUME_NONNULL_BEGIN
@class MealModel;
@interface DetailHeaderView : BaseView
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic,strong) AVPlayerLayer *playerLayer;
@property (nonatomic,strong) UIImageView *background;
- (void)loadData:(MealModel *)data;
@end
NS_ASSUME_NONNULL_END
DetailHeaderView.m代码
#import "DetailHeaderView.h"
#import "MealModel.h"
@implementation DetailHeaderView
- (UIImageView *)background {
if (!_background) {
_background = [[UIImageView alloc] initWithFrame:self.bounds];
_background.image = [UIImage imageNamed:@"视频默认图-1"];
}
return _background;
}
- (AVPlayer *)player {
if (!_player) {
_player = [[AVPlayer alloc] init];
}
return _player;
}
- (AVPlayerLayer *)playerLayer {
if (!_playerLayer) {
_playerLayer = [[AVPlayerLayer alloc] initWithLayer:self.player];
_playerLayer.frame = self.bounds;
_playerLayer.backgroundColor = [UIColor blackColor].CGColor;
_playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
}
return _playerLayer;
}
- (id)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor random];
[self.layer addSublayer:self.playerLayer];
}
return self;
}
- (void)loadData:(MealModel *)data {
if (data.videoDesc.length > 0) {
NSURL *url = [NSURL URLWithString:data.videoDesc];
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
[self.player replaceCurrentItemWithPlayerItem:item];
[self.player play];
} else {
[self addSubview:self.background];
}
}
@end
运行的结果:是(iOS)AVPlayer有声音没有画面!!!
需将
_playerLayer = [[AVPlayerLayer alloc] initWithLayer:self.player];
改为
_playerLayer = [[AVPlayerLayer alloc] init];
再将
[self.player replaceCurrentItemWithPlayerItem:item];
后面添加
[self.playerLayer setPlayer:self.player];
网友评论