操作如下:
__weak typeof(self) weakSelf = self;
self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//当前播放的时间
float current = CMTimeGetSeconds(time);
//总时间
float total = CMTimeGetSeconds(item.duration);
if (current) {
float progress = current / total;
//更新播放进度条
weakSelf.playSlider.value = progress;
weakSelf.currentTime.text = [weakSelf timeFormatted:current];
}
}];
我们可以这个block里面拿到当前播放时间,根据总时间计算出当前播放所占的时间比例,最后更新播放进度条。这里又涉及到了一个数据类类型CMTime,它也是一个结构体,用来作为时间的格式,定义如下:
typedef struct
CMTimeValue value;
CMTimeScale timescale;
CMTimeFlags flags;
CMTimeEpoch epoch;
} CMTime;
CMTime是以分数的形式表示时间,value表示分子,timescale表示分母,flags是位掩码,表示时间的指定状态。所以我们要获得时间的秒数需要分子除以分母。当然你还可以用下面这个函数来获取时间的秒数:
Float64 CMTimeGetSeconds(CMTime time)
最后,当音乐播放完成或者切换音乐时,依然需要移除监听:
if (self.timeObserver) {
[self.player removeTimeObserver:self.timeObserver];
self.timeObserver = nil;
}
7、手动超控(移动滑块)播放进度
这是一个播放音视频很常见的功能,所以强大的AVPlayer理所当然的提供了几个api,下面只讲述其中最简单的一个:
/**
定位播放时间
@param time 指定的播放时间
*/
- (void)seekToTime:(CMTime)time;
具体使用如下:
//移动滑块调整播放进度
- (IBAction)playSliderValueChange:(UISlider *)sender
{
//根据值计算时间
float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration);
//跳转到当前指定时间
[self.player seekToTime:CMTimeMake(time, 1)];
}
8、监听音乐播放完成
一般音视频播放完成时我们或多或少的都要处理一些业务,比如循环播放,播完退出界面等等。下面看下如何监听AVPlayer的播放完成。
//给AVPlayerItem添加播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
这里是采用注册监听AVPlayerItemDidPlayToEndTimeNotification通知,当AVPlayer一播放完成时,便会发出这个通知,我们收到通知后进行处理即可
9、设置音乐后台播放
我们知道运行在ios系统下的程序一旦进入后台就会处于休眠状态,程序停止运行了,也就播放不了什么音乐了。但是有一些特定功能的app还是处于可以后台运行的,比如音乐类型的app正处于这个范畴。但是,并不是说你在应用中播放音乐就能后台高枕无忧的运行了,你依然需要做如下几步操作:










