1、创建AVPlayer播放器
- (AVPlayer *)audioPlayer
{
if (!_audioPlayer) {
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.introModel.url]];
_audioPlayer = [[AVPlayer alloc] initWithPlayerItem:item];;
}
return _audioPlayer;
}
2、播放
//如果上次播放失败,再次播放时就播放不出声音了,所以这里要replace一下
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
[self.audioPlayer replaceCurrentItemWithPlayerItem:item];
[self.audioPlayer play];
3、暂停
[self.audioPlayer pause];
4、播放状态监听
[self.audioPlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
处理状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([object isEqual:self.audioPlayer] && [keyPath isEqualToString:@"status"]) {
NSNumber *status = [change valueForKey:NSKeyValueChangeNewKey];
switch (status.integerValue) {
case AVPlayerStatusUnknown:{
break;
}
case AVPlayerStatusReadyToPlay:{
break;
}
case AVPlayerStatusFailed: {
break;
}
default:
break;
}
}
}
最后别忘了移除KVO
[_audioPlayer removeObserver:self forKeyPath:@"status"];
5、更新当前播放时间
__weak typeof(self) weakself = self;
self.audioObserver = [_audioPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 2) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
__strong typeof(weakself) self = weakself;
if (self.audioPlayer.rate == 1.0) {
[self startPlayAnimation];
} else if (self.audioPlayer.rate == 0.0) {
[self stopPlayAnimation];
}
}];
最后移除时间更新
[_audioPlayer removeTimeObserver:self.audioObserver];
6、添加视频播放通知
//播放完成
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinish:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//播放出错
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playError:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil];
7、当前是否在播放
//iOS 10添加了timeControlStatus标记播放状态,之前版本用rate是否为0来判断播放状态
- (BOOL)isPlaying
{
if ([self.audioPlayer respondsToSelector:@selector(timeControlStatus)]) {
return self.audioPlayer.timeControlStatus == AVPlayerTimeControlStatusPlaying ? true : false;
} else {
if (self.audioPlayer.rate == 0.0) {
return false;
} else {
return true;
}
}
}
网友评论