AVPlayer -【播放音頻.mp3】 學(xué)習(xí) 筆記

基礎(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è)方法");
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容