寫在前面
公司近期要求在App內嵌入音頻播放,由于之前對于音視頻播放只是簡單了解,并沒有系統的研究。這次需要用到的時候就翻閱各種貼子,各個大神的筆記,博客,話說總結是最好的學習方法,所以,自己根據自己的理解,也總結一篇相關的貼子吧,記錄一下。不求有用,但求方便。
一.關于音頻(視頻下篇總結)
一般情況下,播放音頻分為兩種,一種是本地音頻播放,一種是網絡音頻播放。播放本地一般使用AVAudioPlayer,播放網絡文件較多使用AVPlayer,所以下文只針對AVPlayer進行總結。
針對多媒體,蘋果官方打造了一個類庫---AVFoundation框架。這個庫非常強大,專門用來處理音視頻等多媒體技術,而本文主要講AVFoundation下的一個類-----AVPlayer。
什么是AVPlayer?
你可以把它看成是一個已經封裝好的播放器,它的作用可以用來播放視頻和音頻。
二.用法
1.創建工程,導入AVFoundation框架。然后在需要播放音頻的界面創建播放器實例。
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];
player = [[AVPlayer alloc] initWithPlayerItem:item];
2.播放、停止
播放
[player play];
停止
[player pause];
3.監聽播放器的狀態(KVO)
[player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
當status的屬性發生改變,就會觸發觀察者方法的回調。status是AVPlayerItemStatus類型,是一個枚舉類型:
typedefNS_ENUM(NSInteger, AVPlayerItemStatus) {
AVPlayerItemStatusUnknown,//未知狀態
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.監聽音樂的緩存進度(監聽AVPlayer的loadedTimeRanges屬性)
[player addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
回調方法
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;
}
當音樂播放完成,或者切換下一首歌曲時,請務必記得移除觀察者:
[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);
//跳轉到指定時間
[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
程序整個生命周期中設置
AVAudioSession *session = [AVAudioSession sharedInstance];
//設置類型:播放。
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
//激活音頻會話。
[session setActive:YES error:nil];
10.總結
蘋果的原生音視頻處理類庫非常強大,需要深入研究的可以研讀官方API,本文總結的足夠平常的使用,第一次發文,肯定有許多不到之處,希望看官們,嘴下留情,報以寬容的態度給我提出寶貴意見,如本文能給各位帶來哪怕丁點用處,也是值得的。