一、闲谈
一直用着网易云音乐这个app,也一直想要模拟着它做一个却总是懒得迈出第一步,最近终于下定决心,打算先做一点最基础的。一个音乐播放器最基础的当然就是播放管理器了。
二、AVPlayer的入门
其实AVPlayer用起来很简单,我也就不说废话,直接放上代码。
第一步:初始化等操作
// 初始化一个AVPlayer
self.player = [[AVPlayer alloc] init];
// 创建一个item
AVPlayerItem *item =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://m2.music.126.net/lpeVipLJshTxA-T7xjFI2g==/1046735069650768.mp3"]];
// 监听status属性
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
// 监听loadedTimeRanges属性
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
// 设置player的item
[self.player replaceCurrentItemWithPlayerItem:item];
下面再补充一下监听的两个属性。
1.status
这个属性指的是item的状态,状态一共有三种,如下:
typedef NS_ENUM(NSInteger, AVPlayerItemStatus) {
AVPlayerItemStatusUnknown,
AVPlayerItemStatusReadyToPlay,
AVPlayerItemStatusFailed
};
显然,当status为AVPlayerItemStatusReadyToPlay的时候,就说明可以播放了。
2.loadedTimeRanges
这个属性主要是用在获取缓冲的进度的,具体的使用在下文会说到。
第二步:响应监听
既然有监听,那就肯定要响应。先上代码:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
AVPlayerItemStatus status =[change[@"new"]integerValue];//change为string类型
switch (status) {
case AVPlayerItemStatusUnknown:
NSLog(@"AVPlayerItemStatusUnknown");
break;
case AVPlayerItemStatusReadyToPlay:
//调用播放方法
[self.player play];
break;
case AVPlayerItemStatusFailed:{
NSLog(@"AVPlayerItemStatusFailed");
break;
}
default:
break;
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
// 计算缓冲的进度百分比
float timeInterval= [self availableDuration];
NSInteger totalDuration = [self fetchTotalTime];
// 打印缓冲进度的百分比
NSLog(@"进度百分比%f", timeInterval / totalDuration);
}
}
其中监听item的状态的代码就不需要说了,只需要在AVPlayerItemStatusReadyToPlay后加上
[self.player play];
就可以了。
下面讲一下计算缓冲的进度百分比的思路,其实也很简单,先获取到缓冲的进度,再获取到总的时间,然后 缓冲的进度/总时间 就是缓冲的百分比。
自己写一个获取总时间的方法:
// 获取总时间,总秒数
- (NSInteger)fetchTotalTime
{
//获取当前播放歌曲的总时间
CMTime time = self.player.currentItem.duration;
if (time.timescale == 0) {
return 0;
}
//播放秒数 = time.value/time.timescale
return time.value/time.timescale;
}
自己写一个获取缓冲总进度的方法:
- (float)availableDuration
{
NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
float result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
补充一点CMTimeRange的知识:
typedef struct
{
CMTime start; /*! @field start The start time of the time range. */
CMTime duration; /*! @field duration The duration of the time range. */
} CMTimeRange;
start表示的是开始时间,duration表示的是时间范围的持续时间。所以这边缓冲的总进度就是两者相加了。
入门写到这里,下面是自定义一个播放管理器
三、自定义播放管理器
1.创建类并声明方法
想象一下一个播放管理器会有哪些方法,播放,暂停,开始播放网络音乐,开始播放本地音乐,甚至还有拉进度条来快进快退。代码如下:
//单例
+ (instancetype)sharedPlayerManager;
//暂停
- (void)pasuseMusic;
//播放
- (void)playMusic;
//准备去播放
- (void)prepareToPlayMusicWithUrl:(NSString *)url;
//本地播放方法
- (void)prepareToPlayMusicWithFilePath:(NSString *)musicFilePath;
//快进快退方法
- (void)playMusicWithSliderValue:(CGFloat)peogress;
2.相关方法的实现
趁热打铁,先写播放歌曲方法
// 播放网络歌曲
- (void)prepareToPlayMusicWithUrl:(NSString *)url
{
if (!url) {
return;
}
//判断当前有没有正在播放的item
if (self.player.currentItem) {
//移除观察者
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
//创建一个item
AVPlayerItem *item =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
//观察item的加载状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//替换当前item
[self.player replaceCurrentItemWithPlayerItem:item];
//播放完成后自动跳到下一首
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
// 播放本地歌曲
- (void)prepareToPlayMusicWithFilePath:(NSString *)musicFilePath
{
//判断当前有没有正在播放的item
if (self.player.currentItem) {
//移除观察者
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
//创建一个item
AVPlayerItem *item =[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:musicFilePath]];
//观察item的加载状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//替换当前item
[self.player replaceCurrentItemWithPlayerItem:item];
//播放完成后自动跳到下一首
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nextMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
再写相关私有方法
#pragma mark - 私有方法
// 获取当前时间
- (NSInteger)fetchCurrentTime
{
CMTime time = self.player.currentItem.currentTime;
if (time.timescale == 0) {
return 0;
}
return time.value/time.timescale;
}
// 获取总时间时间
- (NSInteger)fetchTotalTime
{
CMTime time = self.player.currentItem.duration;
if (time.timescale == 0) {
return 0;
}
return time.value/time.timescale;
}
// 获取当前播放进度
- (CGFloat)fetchProgressValue
{
return [self fetchCurrentTime]/(CGFloat)[self fetchTotalTime];
}
// 获取缓冲进度
- (float)availableDuration
{
NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
float result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
//将秒数转化成类似00:00的格式,用于界面显示
- (NSString *)changeSecondsTime:(NSInteger)time
{
NSInteger min =time/60;
NSInteger seconds =time % 60;
return [NSString stringWithFormat:@"%.2ld:%.2ld",min,seconds];
}
监听响应
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
AVPlayerItemStatus status =[change[@"new"]integerValue];//change为string类型
switch (status) {
case AVPlayerItemStatusUnknown:
NSLog(@"未知错误");
break;
case AVPlayerItemStatusReadyToPlay:
//调用播放方法
[self.player play];
break;
case AVPlayerItemStatusFailed:{
NSLog(@"错误");
break;
}
default:
break;
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
float timeInterval= [self availableDuration];
NSInteger totalDuration = [self fetchTotalTime];
NSLog(@"==%f", timeInterval / totalDuration);
}
}
由于始终要刷新界面的进度条,所以我们要创建一个timer来时刻返回当前的时间。这里我用的是代理模式。同时加两个开关定时器的私有方法。
// timer懒加载
- (NSTimer *)timer {
if (!_timer) {
_timer =[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
return _timer;
}
//定时器方法
- (void)timerAction {
if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
//1.总时间 2.当期时间 3.当前进度
NSString *totalTime = [self changeSecondsTime:[self fetchTotalTime]];//总时间
NSString *currentTime =[self changeSecondsTime:[self fetchCurrentTime]];//当前时间
CGFloat progress = [self fetchProgressValue];
[self.delegate playManagerDelegateFetchTotalTime:totalTime currentTime:currentTime progress:progress];
}
}
//开启定时器
- (void)startTimer
{
[self.timer fire];
}
//关闭定时器
- (void)closeTimer
{
[self.timer invalidate];
self.timer = nil; //置空
}
最后完成剩下的方法
// 暂停
- (void)pasuseMusic
{
[self.player pause];
[self closeTimer];
}
// 播放
- (void)playMusic
{
[self.player play];
[self startTimer];
}
//快进快退
- (void)playMusicWithSliderValue:(CGFloat)peogress{
//滑动之前 先暂停音乐
[self pasuseMusic];
[self.player seekToTime:CMTimeMake([self fetchTotalTime] * peogress, 1) completionHandler:^(BOOL finished) {
if (finished) {
//活动结束继续播放
[self playMusic];
}
}];
}
好了,到这边所有的方法都完成了。我把代码全部再贴上。
.h文件
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@protocol YQPlayerManagerDelegate <NSObject>
// 传递播放时间总时间等信息
-(void)playManagerDelegateFetchTotalTime:(NSString *)totalTime currentTime:(NSString *)currentTime progress:(CGFloat)progress;
// 传递播放的进度百分比
- (void)playManagerDelegateFetchLoadedTimeRanges:(CGFloat)loadPercent;
// 下一首歌
- (void)playNextMusic;
@end
@interface YQPlayerManager : NSObject
@property (nonatomic, weak) id <YQPlayerManagerDelegate> delegate;
//单例
+ (instancetype)sharedPlayerManager;
//暂停
- (void)pasuseMusic;
//播放
- (void)playMusic;
//准备去播放
- (void)prepareToPlayMusicWithUrl:(NSString *)url;
//本地播放方法
- (void)prepareToPlayMusicWithFilePath:(NSString *)musicFilePath;
//快进快退方法
- (void)playMusicWithSliderValue:(CGFloat)peogress;
@end
.m文件
#import "YQPlayerManager.h"
@interface YQPlayerManager()
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation YQPlayerManager
// timer懒加载
- (NSTimer *)timer {
if (!_timer) {
_timer =[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
return _timer;
}
//定时器方法
- (void)timerAction {
if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchTotalTime:currentTime:progress:)]) {
//1.总时间 2.当期时间 3.当前进度
NSString *totalTime = [self changeSecondsTime:[self fetchTotalTime]];//总时间
NSString *currentTime =[self changeSecondsTime:[self fetchCurrentTime]];//当前时间
CGFloat progress = [self fetchProgressValue];
[self.delegate playManagerDelegateFetchTotalTime:totalTime currentTime:currentTime progress:progress];
}
}
//开启定时器
- (void)startTimer
{
[self.timer fire];
}
//关闭定时器
- (void)closeTimer
{
[self.timer invalidate];
self.timer = nil; //置空
}
//player懒加载
- (AVPlayer *)player
{
if (_player == nil) {
_player = [[AVPlayer alloc] init];
}
return _player;
}
//单例
+ (instancetype)sharedPlayerManager {
static YQPlayerManager *handle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
handle = [[YQPlayerManager alloc] init];
});
return handle;
}
// 暂停
- (void)pasuseMusic
{
[self.player pause];
[self closeTimer];
}
// 播放
- (void)playMusic
{
[self.player play];
[self startTimer];
}
// 播放网络歌曲
- (void)prepareToPlayMusicWithUrl:(NSString *)url
{
if (!url) {
return;
}
//判断当前有没有正在播放的item
if (self.player.currentItem) {
//移除观察者
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
//创建一个item
AVPlayerItem *item =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:url]];
//观察item的加载状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//替换当前item
[self.player replaceCurrentItemWithPlayerItem:item];
//播放完成后自动跳到下一首
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
// 播放本地歌曲
- (void)prepareToPlayMusicWithFilePath:(NSString *)musicFilePath
{
//判断当前有没有正在播放的item
if (self.player.currentItem) {
//移除观察者
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
//创建一个item
AVPlayerItem *item =[AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:musicFilePath]];
//观察item的加载状态
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//替换当前item
[self.player replaceCurrentItemWithPlayerItem:item];
//播放完成后自动跳到下一首
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nextMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}
//快进快退
- (void)playMusicWithSliderValue:(CGFloat)peogress{
//滑动之前 先暂停音乐
[self pasuseMusic];
[self.player seekToTime:CMTimeMake([self fetchTotalTime] * peogress, 1) completionHandler:^(BOOL finished) {
if (finished) {
//活动结束继续播放
[self playMusic];
}
}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"status"]) {
AVPlayerItemStatus status =[change[@"new"]integerValue];//change为string类型
switch (status) {
case AVPlayerItemStatusUnknown:
NSLog(@"未知错误");
break;
case AVPlayerItemStatusReadyToPlay:
// 调用播放方法
// 注意这里要改成[self playMusic];而不是还是原来的[self.player play],否则无法开启定时器!!!
[self playMusic];
break;
case AVPlayerItemStatusFailed:{
NSLog(@"错误");
break;
}
default:
break;
}
} else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
float timeInterval= [self availableDuration];
NSInteger totalDuration = [self fetchTotalTime];
float percent = timeInterval /totalDuration;
if (percent > 1) {
percent = 1;
}
if ([self.delegate respondsToSelector:@selector(playManagerDelegateFetchLoadedTimeRanges:)]) {
[self.delegate playManagerDelegateFetchLoadedTimeRanges:percent];
}
}
}
#pragma mark - 私有方法
- (void)nextMusic
{
if ([self.delegate respondsToSelector:@selector(playNextMusic)]) {
[self.delegate playNextMusic];
}
}
// 获取当前时间
- (NSInteger)fetchCurrentTime
{
CMTime time = self.player.currentItem.currentTime;
if (time.timescale == 0) {
return 0;
}
return time.value/time.timescale;
}
// 获取总时间时间
- (NSInteger)fetchTotalTime
{
CMTime time = self.player.currentItem.duration;
if (time.timescale == 0) {
return 0;
}
return time.value/time.timescale;
}
// 获取当前播放进度
- (CGFloat)fetchProgressValue
{
return [self fetchCurrentTime]/(CGFloat)[self fetchTotalTime];
}
// 获取缓冲进度
- (float)availableDuration
{
NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
float result = startSeconds + durationSeconds;// 计算缓冲总进度
return result;
}
//将秒数转化成类似00:00的格式,用于界面显示
- (NSString *)changeSecondsTime:(NSInteger)time
{
NSInteger min =time/60;
NSInteger seconds =time % 60;
return [NSString stringWithFormat:@"%.2ld:%.2ld",min,seconds];
}
3.使用管理器
在视图控制器中使用,上代码:
- (void)viewDidLoad
{
[super viewDidLoad];
YQPlayerManager *manager = [YQPlayerManager sharedPlayerManager];
[manager prepareToPlayMusicWithUrl:@"http://m2.music.126.net/lpeVipLJshTxA-T7xjFI2g==/1046735069650768.mp3"];
manager.delegate = self;
}
- (void)playManagerDelegateFetchTotalTime:(NSString *)totalTime currentTime:(NSString *)currentTime progress:(CGFloat)progress
{
NSLog(@"%@---%@---%f", totalTime, currentTime, progress);
}
- (void)playManagerDelegateFetchLoadedTimeRanges:(CGFloat)loadPercent
{
NSLog(@"%f", loadPercent);
}
- (void)playNextMusic
{
NSLog(@"playNextMusic");
}
结果:
最后
到这里就全部搞定了,喜欢的点个赞呗~