AVPlayer使用
app集成了视频与音频播放功能,完成程序后总结下播放功能的实现。
MBAAudioPlayer对AVPlayer进行了封装,代码在最下面。
- 了解AVPlayer
AVPlayer是一个可以播放任何格式的全功能影音播放器。
支持视频格式: WMV,AVI,MKV,RMVB,RM,XVID,MP4,3GP,MPG等。
支持音频格式:MP3,WMA,RM,ACC,OGG,APE,FLAC,FLV等。
在创建一个播放器之前我们需要先了解一些播放器相关的类
- AVPlayer:控制播放器的播放,暂停,播放速度
- AVURLAsset : AVAsset 的一个子类,使用 URL 进行实例化,实例化对象包换 URL 对应视频资源的所有信息。
- AVPlayerItem:管理资源对象,提供播放数据源
- AVPlayerLayer:负责显示视频,如果没有添加该层,只有声音没有画面
- 实现思路
2.1 通过一个网络链接或本地地址播放
2.2 播放器的常用操作: 播放 or 暂停
2.3 播放item
2.4 seekToTime指定从某一秒开始播放
- (void)seekToTime:(CMTime)time completionHandler:(void (^)(BOOL finished))completionHandler NS_AVAILABLE(10_7, 5_0);
2.5 监听播放进度
addPeriodicTimeObserverForInterval:queue:usingBlock:
2.6 监听改播放器状态
[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
2.7 监听AVPlayer播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
- 实现封装
3.1 播放器初始化:提供了类方法与单例方法
// 创建单例
+ (instancetype)sharedAudioPlayer;
+ (instancetype)audioPlayer;
3.2 使用过程中需要使用的回调或赋值
@property (copy, nonatomic) void(^playingUIHander)(float currentTime);
@property (copy, nonatomic) void(^playerLoadFailHander)();
@property (copy, nonatomic) void(^playerLoadSuceessHander)(float audioDuration);
@property (copy, nonatomic) void(^playerEndHander)();
@property (copy, nonatomic) void(^playerSeekToTimeHander)();
@property (strong, nonatomic) AVPlayerLayer *playerLayer;//mp4的时候需要用
@property (assign, nonatomic) CGFloat currentTime;
@property (assign, nonatomic) CGFloat durationTime;//总时长,加载成功才会有值(默认0)
@property (nonatomic, assign) BOOL isPlaying;
-(void)playWithURL:(NSURL *)url;
-(void)play;
-(void)pause;
-(void)playAtTime:(NSTimeInterval)time;
-(void)playTimeAddTime:(NSTimeInterval)time;//前进或后退time秒
-(void)removeObserveAndNotification;
全部详细代码如下:
MBAAudioPlayer.h
//
// MBAAudioPlayer.h
// MBALib
//
// Created by mba on 2017/9/11.
// Copyright © 2017年 mbalib. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
@interface MBAAudioPlayer : NSObject
// 创建单例
+ (instancetype)sharedAudioPlayer;
+ (instancetype)audioPlayer;
@property (copy, nonatomic) void(^playingUIHander)(float currentTime);
@property (copy, nonatomic) void(^playerLoadFailHander)();
@property (copy, nonatomic) void(^playerLoadSuceessHander)(float audioDuration);
@property (copy, nonatomic) void(^playerEndHander)();
@property (copy, nonatomic) void(^playerSeekToTimeHander)();
@property (strong, nonatomic) AVPlayerLayer *playerLayer;//mp4的时候需要用
@property (assign, nonatomic) CGFloat currentTime;
@property (assign, nonatomic) CGFloat durationTime;//总时长,加载成功才会有值(默认0)
@property (nonatomic, assign) BOOL isPlaying;
-(void)playWithURL:(NSURL *)url;
-(void)play;
-(void)pause;
-(void)playAtTime:(NSTimeInterval)time;
-(void)playTimeAddTime:(NSTimeInterval)time;//前进或后退time秒
-(void)removeObserveAndNotification;
@end
MBAAudioPlayer.m
//
// MBAAudioPlayer.m
// MBALib
//
// Created by mba on 2017/9/11.
// Copyright © 2017年 mbalib. All rights reserved.
//
#import "MBAAudioPlayer.h"
#import <AFNetworking/AFNetworking.h>
@interface MBAAudioPlayer ()
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (strong, nonatomic) id playTimeObserver;
@property (assign, nonatomic) BOOL isBackEnter;//是否后台进入
@end
@implementation MBAAudioPlayer
// 创建单例
+ (instancetype)sharedAudioPlayer{
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[MBAAudioPlayer alloc] init];
});
return instance;
}
+ (instancetype)audioPlayer{
return [[self alloc] init];
}
-(instancetype)init
{
if(self = [super init])
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
}
return self;
}
-(void)applicationDidEnterBackground{
self.isBackEnter = true;
_playerLayer.player = nil;
}
-(void)applicationWillEnterForeground{
self.isBackEnter = true;
_playerLayer.player = _player;
}
-(void)playWithURL:(NSURL *)url{
self.isBackEnter = false;
self.durationTime = 0;
[self removeObserveAndNotification];
[self setPlayUIWithPlayTime:0];
_playerItem = [AVPlayerItem playerItemWithURL:url];
_player = [AVPlayer playerWithPlayerItem:_playerItem];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.videoGravity = @"AVLayerVideoGravityResize";
[self addObserverAndNotification];
}
-(void)dealloc{
[self removeObserveAndNotification];
}
-(void)play{
[self.player play];
}
-(void)pause{
[self.player pause];
}
-(CGFloat)currentTime{
return CMTimeGetSeconds(self.player.currentTime);
}
-(BOOL)isPlaying{
return (self.player.rate >= 1);
}
-(void)playAtTime:(NSTimeInterval)time{
[self.player pause];
[self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
[self.player play];
if (self.playerSeekToTimeHander) {
self.playerSeekToTimeHander();
}
}];
}
-(void)playTimeAddTime:(NSTimeInterval)time{
[self playAtTime:CMTimeGetSeconds(self.player.currentTime) + time];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
AVPlayerItem *item = (AVPlayerItem *)object;
if ([keyPath isEqualToString:@"status"]) {
AVPlayerStatus status = [[change objectForKey:@"new"] intValue]; // 获取更改后的状态
if (status == AVPlayerStatusReadyToPlay) {
CMTime duration = item.duration; // 获取视频长度
self.durationTime = CMTimeGetSeconds(duration);
// 设置视频时间
if (!self.isBackEnter && self.playerLoadSuceessHander) {
self.playerLoadSuceessHander(self.durationTime);
}
} else if (status == AVPlayerStatusFailed) {
NSLog(@"AVPlayerStatusFailed");
if (self.playerLoadFailHander) {
self.playerLoadFailHander();
}
} else {
NSLog(@"AVPlayerStatusUnknown");
if (self.playerLoadFailHander) {
self.playerLoadFailHander();
}
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
// NSTimeInterval timeInterval = [self availableDurationRanges]; // 缓冲时间
// CGFloat totalDuration = CMTimeGetSeconds(_playerItem.duration); // 总时间
// [self.loadedProgress setProgress:timeInterval / totalDuration animated:YES]; // 更新缓冲条
} else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) { //监听播放器在缓冲数据的状态
// NSLog(@"缓冲不足暂停了");
} else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
// NSLog(@"缓冲达到可播放程度了");
//由于 AVPlayer 缓存不足就会自动暂停,所以缓存充足了需要手动播放,才能继续播放
[_player play];
}
}
// 观察播放进度
- (void)monitoringPlayback:(AVPlayerItem *)item {
__weak typeof(self)WeakSelf = self;
// 观察间隔, CMTime 为30分之一秒
_playTimeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 30.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float currentPlayTime = (double)item.currentTime.value/ item.currentTime.timescale;
[WeakSelf setPlayUIWithPlayTime:currentPlayTime];
}];
}
-(void)setPlayUIWithPlayTime:(float)currentTime{
if (self.playingUIHander) {
self.playingUIHander(currentTime);
}
}
// 播放完成后
- (void)playbackFinished:(NSNotification *)notification {
// MBALog(@"视频播放完成通知");
_playerItem = [notification object];
[_playerItem seekToTime:kCMTimeZero]; // item 跳转到初始
//[_player play]; // 循环播放
if (self.playerEndHander) {
self.playerEndHander();
}
}
-(void)addObserverAndNotification{
[_playerItem addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil]; // 观察status属性,
[self monitoringPlayback:_playerItem];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
-(void)removeObserveAndNotification{
if (_playerItem == nil || _player == nil) return;
@try {
[_playerItem removeObserver:self forKeyPath:@"status" context:nil];
}
@catch (NSException *exception) {
// NSLog(@"多次删除kvo 报错了");
}
[_player removeTimeObserver:_playTimeObserver]; // 移除playTimeObserver
[_playerItem cancelPendingSeeks];
[_playerItem.asset cancelLoading];
[_playerLayer removeFromSuperlayer];
_player = nil;
_playerItem = nil;
_playerLayer = nil;
_playTimeObserver = nil;
[[NSNotificationCenter defaultCenter]removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
@end