iOS 網(wǎng)絡(luò)音頻播放 AVPlayer

寫在前面

公司近期要求在App內(nèi)嵌入音頻播放,由于之前對于音視頻播放只是簡單了解,并沒有系統(tǒng)的研究。這次需要用到的時候就翻閱各種貼子,各個大神的筆記,博客,話說總結(jié)是最好的學(xué)習(xí)方法,所以,自己根據(jù)自己的理解,也總結(jié)一篇相關(guān)的貼子吧,記錄一下。不求有用,但求方便。

一.關(guān)于音頻(視頻下篇總結(jié))

一般情況下,播放音頻分為兩種,一種是本地音頻播放,一種是網(wǎng)絡(luò)音頻播放。播放本地一般使用AVAudioPlayer,播放網(wǎng)絡(luò)文件較多使用AVPlayer,所以下文只針對AVPlayer進行總結(jié)。

針對多媒體,蘋果官方打造了一個類庫---AVFoundation框架。這個庫非常強大,專門用來處理音視頻等多媒體技術(shù),而本文主要講AVFoundation下的一個類-----AVPlayer。

什么是AVPlayer?

你可以把它看成是一個已經(jīng)封裝好的播放器,它的作用可以用來播放視頻和音頻。

二.用法

1.創(chuàng)建工程,導(dǎo)入AVFoundation框架。然后在需要播放音頻的界面創(chuàng)建播放器實例。

AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];

player = [[AVPlayer alloc] initWithPlayerItem:item];

2.播放、停止

播放

[player play];

停止

[player pause];

3.監(jiān)聽播放器的狀態(tài)(KVO)

[player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

當status的屬性發(fā)生改變,就會觸發(fā)觀察者方法的回調(diào)。status是AVPlayerItemStatus類型,是一個枚舉類型:

typedefNS_ENUM(NSInteger, AVPlayerItemStatus) {

AVPlayerItemStatusUnknown,//未知狀態(tài)

AVPlayerItemStatusReadyToPlay,//準備播放

AVPlayerItemStatusFailed//加載失敗

};

只有當player.status == AVPlayerStatusReadyToPlay時,才能正常播放音樂。

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context;

記得移除觀察者

[player removeObserver:self forKeyPath:@"status"];

4.切換音樂

AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url2];

替換當前的音樂資源

[player replaceCurrentItemWithPlayerItem:item];

5.監(jiān)聽音樂的緩存進度(監(jiān)聽AVPlayer的loadedTimeRanges屬性)

[player addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];

回調(diào)方法

if([keyPath isEqualToString:@"loadedTimeRanges"]) {

NSArray * timeRanges = player.currentItem.loadedTimeRanges;

//本次緩沖的時間范圍

CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];

//緩沖總長度

NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);

//音樂的總時間

NSTimeInterval duration = CMTimeGetSeconds(player.currentItem.duration);

//計算緩沖百分比例

NSTimeInterval scale = totalLoadTime/duration;

//更新緩沖進度條

self.loadTimeProgress.progress = scale;

}

當音樂播放完成,或者切換下一首歌曲時,請務(wù)必記得移除觀察者:

[player addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];

6.音樂播放進度(AVPlayer提供了方法)

- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;

__weak typeof(self) weakSelf = self;

self.timeObserver = [player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

//當前播放的時間

floatcurrent = CMTimeGetSeconds(time);

//總時間

floattotal = CMTimeGetSeconds(item.duration);

if(current) {

floatprogress = current / total;

//更新播放進度條

weakSelf.playSlider.value = progress;

weakSelf.currentTime.text = [weakSelf timeFormatted:current];

}

}];

7.拖動指定位置播放

- (void)seekToTime:(CMTime)time;

- (IBAction)playSliderValueChange:(UISlider *)sender{

//計算時間

floattime= sender.value * CMTimeGetSeconds(player.currentItem.duration);

//跳轉(zhuǎn)到指定時間

[player seekToTime:CMTimeMake(time, 1)];

}

8.播放完成(通知)

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:player.currentItem];

9.后臺播放

開啟后臺模式

target ->capabilities ->background modes->勾選Audio,AirPlay,and Picture in Picture


程序整個生命周期中設(shè)置

AVAudioSession *session = [AVAudioSession sharedInstance];

//設(shè)置類型:播放。

[session setCategory:AVAudioSessionCategoryPlayback error:nil];

//激活音頻會話。

[session setActive:YES error:nil];

10.總結(jié)

蘋果的原生音視頻處理類庫非常強大,需要深入研究的可以研讀官方API,本文總結(jié)的足夠平常的使用,第一次發(fā)文,肯定有許多不到之處,希望看官們,嘴下留情,報以寬容的態(tài)度給我提出寶貴意見,如本文能給各位帶來哪怕丁點用處,也是值得的。

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

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

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