基礎(chǔ)功能:
暫停 [_player pause];
播放 [_player play];
注意:下一曲,上一曲時(shí),一定要移除kvo不然會(huì)報(bào)錯(cuò)!??!
初始化:
@property (nonatomic,strong) AVPlayer * player;
-(AVPlayer *)player{
if (_player == nil) {
_player = [[AVPlayer alloc] init];
_player.volume = 1.0; // 默認(rèn)最大音量
}
return _player;
}
播放URL 的方法,傳入U(xiǎn)RL
- (void)P_musicPlayerWithURL:(NSURL *)playerItemURL{
// 移除監(jiān)聽(tīng)
// [self p_currentItemRemoveObserver];
// 創(chuàng)建要播放的資源
AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:playerItemURL];
// 播放當(dāng)前資源
[self.player replaceCurrentItemWithPlayerItem:playerItem];
// 添加觀察者
// [self p_currentItemAddObserver];
}
// 播放 本地音頻,將本地文件 轉(zhuǎn)成 url 傳入
NSString * audioPath = [[NSBundle mainBundle]pathForResource:@"小蘋(píng)果" ofType:@".mp3"];
[self p_musicPlayerWithURL:[NSURL fileURLWithPath:audioPath]];
進(jìn)度條跟隨播放時(shí)間 改變進(jìn)度 方法:
1.創(chuàng)建一個(gè) 全局的 定時(shí)器 timer ,重復(fù)調(diào)用定時(shí)器
self.avTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
2.在定時(shí)器調(diào)用方法里設(shè)置滑塊的值
- (void)timer{
_progress.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
// 顯示播放時(shí)間的Label
_timeLabel_Play.text = [self changeTimeToCurrentDate:CMTimeGetSeconds(self.player.currentItem.currentTime)];
//顯示歌曲總長(zhǎng)度的Label
_timeLabel_End.text = [self changeTimeToCurrentDate:CMTimeGetSeconds(self.player.currentItem.duration)];
}
拖動(dòng)滑塊,改變 播放進(jìn)度
/滑塊滑動(dòng)方法
-
(void) sliderValueChanged:(UISlider*)sender{
//暫停定時(shí)器
[_avTimer setFireDate:[NSDate distantFuture]];
// 拖動(dòng)改變音樂(lè)播放進(jìn)度
if (_player.status == AVPlayerItemStatusReadyToPlay) {
// 總秒數(shù)
CGFloat total = (CGFloat)_playerItem.duration.value / _playerItem.duration.timescale;
// 已經(jīng)拖動(dòng)到了現(xiàn)在的秒數(shù)了。
NSInteger dragedSeconds = floorf(total * sender.value);
//轉(zhuǎn)換成CMTime才能給player來(lái)控制播放進(jìn)度---這個(gè)類(lèi)用來(lái)控制時(shí)間的。
CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
[_player pause];
//改變顯示時(shí)間方法
_timeLabel_Play.text = [self changeTimeToCurrentDate:dragedSeconds];
[_player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {[_player play]; }];}
NSLog(@"滑塊拖動(dòng)調(diào)用這個(gè)方法");
}