在iOS多媒体开发的过程中,经常会用到视频播放器,简单是视频播放器,直接使用苹果封装好的MPMoviePlayerController和MPMoviePlayerViewController就可以实现视频播放功能了,但是,多数情况下,都需要自定制视频播放器,这是,就要使用神器AVPlayer来进行开发了,下面,就讲述一下AVPlayer的使用,这里列出两篇比较好的博客,供大家参考:
iOS开发系列--音频播放、录音、视频播放、拍照、视频录制
#import
@property (nonatomic,strong) AVPlayer * player;
//网络视频
NSString * urlStr = [NSString stringWithFormat:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL * url = [NSURL URLWithString:urlStr];
self.player = [[AVPlayer alloc] initWithURL:url];
@property (nonatomic,strong) AVPlayerLayer * playerLayer;
self.player = [[AVPlayer alloc] initWithURL:url];
self.playerLayer.frame = self.layer.bounds;
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.layer addSublayer:self.playerLayer];
@property (nonatomic,strong) AVPlayerItem * playerItem;
AVURLAsset * movieAsset = [[AVURLAsset alloc] initWithURL:URL options:nil];
self.playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.layer.bounds;
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.layer addSublayer:self.playerLayer];
/**
* 监听AVPlayerItem的属性
*/
[self.playerItem addObserver:self forKeyPath:@"status" options:0 context:NULL];
[self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:0 context:NULL];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
/**
* KVO监听playItem的属性变化
*
* @param keyPath keyPath description
* @param object object description
* @param change change description
* @param context context description
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
AVPlayerItem * item = self.player.currentItem;
if ([keyPath isEqualToString:@"status"]) {
//正在播放
if (AVPlayerItemStatusReadyToPlay == item.status) {
NSLog(@"正在播放...,视频总长度:%.2f",CMTimeGetSeconds(item.duration));
}
else if (AVPlayerItemStatusUnknown == item.status){
NSLog(@"视频加载中");
}
else if (AVPlayerStatusFailed == item.status){
NSLog(@"视频获取失败");
NSLog(@"%@",item.error);
}
} else if([keyPath isEqualToString:@"loadedTimeRanges"]){
NSArray *array=item.loadedTimeRanges;
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
NSLog(@"共缓冲:%.2f",totalBuffer);
}
}
[self.player play];
//移除观察者
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
[playerItem removeObserver:self forKeyPath:@"status"];
[playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
/**
* 添加播放器通知
*/
-(void)addNotification{
//给AVPlayerItem添加播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
- (void)playbackFinished:(NSNotification *)notification{
[self.playButton setImage:[UIImage imageNamed:@"button_normal"] forState:UIControlStateNormal];
}
[self removeNotification];
//当前播放进度
@property (nonatomic,assign) double currentTime;
/**
* 开始播放
*/
- (void)play{
AVPlayerItem * item = self.player.currentItem;
// [item seekToTime:CMTimeMakeWithSeconds(0, 1.0)];
[item seekToTime:CMTimeMakeWithSeconds(0, 1.0) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
self.progressBar.value = 0;
[self.player play];
//设置播放速度
}
/**
* 暂停播放
*/
- (void)pause{
self.currentTime = [self playableCurrentTime];
[self.player pause];
//设置播放按钮
[self.playButton setImage:[UIImage imageNamed:@"button_normal"] forState:UIControlStateNormal];
}
/**
* 继续播放
*/
- (void)resume{
AVPlayerItem * item = self.player.currentItem;
// [item seekToTime:CMTimeMakeWithSeconds(self.currentTime, 1.0)];
[item seekToTime:CMTimeMakeWithSeconds(self.currentTime, 1.0) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[self.player play];
//设置播放速度
self.player.rate = self.rate;
}
/**
* 停止
*/
- (void)stop{
AVPlayerItem * item = self.player.currentItem;
// [item seekToTime:CMTimeMakeWithSeconds(0, 1.0)];
[item seekToTime:CMTimeMakeWithSeconds(0, 1.0) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[self.player pause];
self.currentTime = 0;
}
//音量
@property (nonatomic,assign) float volumn;
/**
* 设置静音
*
* @param mute 静音传入的一个BOOL值,YES为静音,NO不静音
*/
- (void)playerMute:(BOOL)mute{
if (mute) {
[self.player setVolume:0];
} else {
[self.player setVolume:self.volumn];
}
}
/**
* 进度更新设置,监听视频播放进度,同时更新进度条的value
*/
- (void)addProgressBarObserver{
AVPlayerItem *playerItem=self.player.currentItem;
__weak typeof(self) weakSelf = self;
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float current = CMTimeGetSeconds(time);
float total = CMTimeGetSeconds([playerItem duration]);
if (current) {
[weakSelf.progressBar setValue:(current/total) animated:YES];
}
}];
}
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;
通过以上的方法,基本上就能实现一个简单的视频播放器了,可能有些地方说的不好或者说法有误,欢迎大家在下面进行评论,指出我的错误,大家共同进步。想进一步了解视频播放器的内容,欢迎阅读下一篇博客:
AVPlayer自定制视频播放器(2)——耳机线控、中断以及AVAudioSession的使用