最近工作需要用到媒体播放器,所以开始在看这方面的资料。
先是做了一个使用 AVPlayer 播放网络视频的 Demo, 由于需要使用 rtsp 协议连接设备来进行视频实时播放,AVFoundation 并不对此进行支持。
不过既然做了,就还是做一下笔记吧。
如果需要简单的播放 http 协议的网络视频,可以直接套用。
1. 基本步骤
1.1 自定义播放视图
该视图就是播放器的载体。
主要是要重设该视图的 Layer,让他成为 AVPlayerLayer,才能用来播放视频。
NJPreviewPlayerView.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface NJPreviewPlayerView : UIView
- (void)setPlayer:(AVPlayer *)player;
@end
NJPreviewPlayerView.m
#import "NJPreviewPlayerView.h"
#import "FFMpegPlayer.h"
@interface NJPreviewPlayerView()
@property (nonatomic) AVPlayer *player;
@end
@implementation NJPreviewPlayerView
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer*)player {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setPlayer:(AVPlayer *)player {
[(AVPlayerLayer *)[self layer] setVideoGravity:AVLayerVideoGravityResize];
[(AVPlayerLayer *)[self layer] setPlayer:player];
}
@end
1.2 配置与控制播放器
设置属性 AVPlayer,AVPlayerItem。如果是本地视频还有一个 AVAssets。
基本流程:配置 AVPlayerItem,配置 AVPlayer,监听 AVPlayerItem 状态,然后进行播放。
主要代码在 configurationPlayer 以及 observeValueForKeyPath 中。
NJPreviewPlayerView.h
#import <UIKit/UIKit.h>
#import "NJPreviewPlayerView.h"
@interface NJPreviewViewController : UIViewController
@end
NJPreviewPlayerView.m
#import "NJPreviewViewController.h"
@interface NJPreviewViewController ()
@property (weak, nonatomic) IBOutlet NJPreviewPlayerView *preview;
@property (nonatomic) AVPlayer * player;
@property (nonatomic) AVPlayerItem * playerItem;
@end
@implementation NJPreviewViewController
#pragma mark - Lift cycle
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self configurationPlayer];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
[self removeObservers];
}
#pragma mark - Preview
- (void)configurationPlayer {
NSURL * url = [NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
self.playerItem = [AVPlayerItem playerItemWithURL:url];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
[self setObservers];
[self.preview setPlayer:self.player];
}
#pragma mark - KVO
- (void)setObservers {
[self.playerItem addObserver:self forKeyPath:@"status" options:0 context:nil];
}
- (void)removeObservers {
[self.playerItem removeObserver:self forKeyPath:@"status"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"status"]) {
NSLog(@"%@", self.playerItem.error);
switch (self.playerItem.status) {
case AVPlayerItemStatusReadyToPlay:
NSLog(@"AVPlayerItemStatusReadyToPlay");
[self.player play];
break;
case AVPlayerItemStatusUnknown:
NSLog(@"AVPlayerItemStatusUnknown");
break;
case AVPlayerItemStatusFailed:
NSLog(@"AVPlayerItemStatusFailed");
break;
}
}
}
@end
2. 参考资料
我用到的就是这么简单的,所以没有写复杂,但是其实 AVFoundation 家族非常强大,录音,录像也可以用它来做。
具体参考官方文档,讲得非常详细。
网友评论