版本記錄
版本號 | 時間 |
---|---|
V1.0 | 2017.12.26 |
前言
ios系統中有很多方式可以播放音頻文件,這里我們就詳細的說明下播放音樂文件的原理和實例。感興趣的可以看我寫的上面幾篇。
1. 幾種播放音頻文件的方式(一) —— 播放本地音樂
2. 幾種播放音頻文件的方式(二) —— 音效播放
功能要求
播放網絡音樂
功能實現
1. 模塊說明
下面我們就分模塊進行說明
創建AVPlayerItem
- (AVPlayerItem *)getItemWithIndex:(NSInteger)index
{
NSURL *url = [NSURL URLWithString:self.musicArray[index]];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
//KVO監聽播放狀態
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//KVO監聽緩存大小
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//通知監聽item播放完畢
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playOver:) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
return item;
}
實現KVO的方法,根據keyPath來判斷觀察的屬性
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
AVPlayerItem *item = object;
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
NSLog(@"未知狀態,不能播放");
break;
case AVPlayerStatusReadyToPlay:
NSLog(@"準備完畢,可以播放");
break;
case AVPlayerStatusFailed:
NSLog(@"加載失敗, 網絡相關問題");
break;
default:
break;
}
}
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray *array = item.loadedTimeRanges;
//本次緩存的時間
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
NSTimeInterval totalBufferTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //緩存的總長度
self.bufferProgress.progress = totalBufferTime / CMTimeGetSeconds(item.duration);
}
}
加載AVPlayer
- (AVPlayer *)player
{
if (!_player) {
// 根據鏈接數組獲取第一個播放的item, 用這個item來初始化AVPlayer
AVPlayerItem *item = [self getItemWithIndex:self.currentIndex];
// 初始化AVPlayer
_player = [[AVPlayer alloc] initWithPlayerItem:item];
__weak typeof(self)weakSelf = self;
// 監聽播放的進度的方法,addPeriodicTime: ObserverForInterval: usingBlock:
/*
DMTime 每到一定的時間會回調一次,包括開始和結束播放
block回調,用來獲取當前播放時長
return 返回一個觀察對象,當播放完畢時需要,移除這個觀察
*/
_timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float current = CMTimeGetSeconds(time);
if (current) {
[weakSelf.progressView setProgress:current / CMTimeGetSeconds(item.duration) animated:YES];
weakSelf.progressSlide.value = current / CMTimeGetSeconds(item.duration);
}
}];
}
return _player;
}
播放和暫停
//播放
[self.player play];
//暫停
[self.player pause];
下一首和上一首
- (IBAction)next:(UIButton *)sender
{
[self removeObserver];
self.currentIndex ++;
if (self.currentIndex >= self.musicArray.count) {
self.currentIndex = 0;
}
// 這個方法是用一個item取代當前的item
[self.player replaceCurrentItemWithPlayerItem:[self getItemWithIndex:self.currentIndex]];
[self.player play];
}
- (IBAction)last:(UIButton *)sender
{
[self removeObserver];
self.currentIndex --;
if (self.currentIndex < 0) {
self.currentIndex = 0;
}
// 這個方法是用一個item取代當前的item
[self.player replaceCurrentItemWithPlayerItem:[self getItemWithIndex:self.currentIndex]];
[self.player play];
}
// 在播放另一個時,要移除當前item的觀察者,還要移除item播放完成的通知
- (void)removeObserver
{
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
控制播放進度
如果不是太精確,用- (void)seekToTime:(CMTime)time:
這個方法就行,如果要精確的用這個- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter
。
if (self.player.status == AVPlayerStatusReadyToPlay) {
[self.player seekToTime:CMTimeMake(CMTimeGetSeconds(self.player.currentItem.duration) * sender.value, 1)];
}
下面我們就看一下這兩個方法的API
/*!
@method seekToTime:
@abstract Moves the playback cursor.
@param time
@discussion Use this method to seek to a specified time for the current player item.
The time seeked to may differ from the specified time for efficiency. For sample accurate seeking see seekToTime:toleranceBefore:toleranceAfter:.
*/
- (void)seekToTime:(CMTime)time;
/*!
@method seekToTime:toleranceBefore:toleranceAfter:
@abstract Moves the playback cursor within a specified time bound.
@param time
@param toleranceBefore
@param toleranceAfter
@discussion Use this method to seek to a specified time for the current player item.
The time seeked to will be within the range [time-toleranceBefore, time+toleranceAfter] and may differ from the specified time for efficiency.
Pass kCMTimeZero for both toleranceBefore and toleranceAfter to request sample accurate seeking which may incur additional decoding delay.
Messaging this method with beforeTolerance:kCMTimePositiveInfinity and afterTolerance:kCMTimePositiveInfinity is the same as messaging seekToTime: directly.
*/
- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter;
2. 代碼實現
下面我們就看一下代碼實現。
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) UISlider *progressSlide;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIImageView *animatedView;
@property (nonatomic, strong) id timeObserver;
@end
@implementation ViewController
#pragma mark - Override Base Function
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//UI界面
[self initUI];
//可播放可錄音,更可以后臺播放,還可以在其他程序播放的情況下暫停播放
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
error:nil];
}
- (void)dealloc
{
[self.player.currentItem removeObserver:self forKeyPath:@"status"];
[self.player.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
if (self.timeObserver) {
[self.player removeTimeObserver:self.timeObserver];
self.timeObserver = nil;
}
}
#pragma mark - Object Private Function
- (void)initUI
{
//背景圖案
self.animatedView = [[UIImageView alloc] init];
self.animatedView.image = [UIImage imageNamed:@"backView"];
self.animatedView.frame = CGRectMake((self.view.bounds.size.width - 200.0) * 0.5, (self.view.bounds.size.height - 200.0) * 0.5, 200.0, 200.0);
self.animatedView.layer.cornerRadius = 100.0;
self.animatedView.layer.masksToBounds = YES;
[self.view addSubview:self.animatedView];
//開始按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake((self.view.bounds.size.width - 200.0) * 0.5, (self.view.bounds.size.height - 200.0) * 0.5, 200.0, 200.0);
button.layer.cornerRadius = 100.0;
button.layer.masksToBounds = YES;
[button setTitle:@"開始播放" forState:UIControlStateNormal];
[button setTitle:@"停止播放" forState:UIControlStateSelected];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[button addTarget:self action:@selector(playButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
self.button = button;
//滑動條
UISlider *progressSlide = [[UISlider alloc] initWithFrame:CGRectMake(30.0, self.view.bounds.size.height - 100.0, self.view.bounds.size.width - 60.0, 50.0)];
progressSlide.backgroundColor = [UIColor purpleColor];
[progressSlide addTarget:self action:@selector(sliderDidSlide:) forControlEvents:UIControlEventValueChanged];
self.progressSlide = progressSlide;
[self.view addSubview:progressSlide];
}
- (void)playMusic
{
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
[self.player play];
}
- (void)stopMusic
{
[self.player pause];
}
- (AVPlayerItem *)getItemWithIndex:(NSInteger)index
{
//這里是用本地數據模擬網絡數據,網絡資源不好找
// NSString *str = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"m4a"];
NSString *str = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath:str];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
//KVO監聽播放狀態
[item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
//KVO監聽緩存大小
[item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
//通知監聽item播放完畢
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopMusic) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
return item;
}
#pragma mark - Action && Notification
- (void)playButtonDidClick:(UIButton *)button
{
button.selected = !button.selected;
if (button.selected) {
[self playMusic];
}
else {
[self stopMusic];
self.player = nil;
if (_timer) {
[_timer invalidate];
_timer = nil;
}
self.animatedView.transform = CGAffineTransformMakeRotation(0.0);
self.progressSlide.value = 0.0;
}
}
- (void)sliderDidSlide:(UISlider *)slider
{
NSLog(@"拖動");
if (self.player.status == AVPlayerStatusReadyToPlay) {
[self.player seekToTime:CMTimeMake(CMTimeGetSeconds(self.player.currentItem.duration) * slider.value, 1)];
}
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
AVPlayerItem *item = object;
//狀態的監聽
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
NSLog(@"未知狀態,不能播放");
break;
case AVPlayerStatusReadyToPlay:
NSLog(@"準備完畢,可以播放");
break;
case AVPlayerStatusFailed:
NSLog(@"加載失敗, 網絡相關問題");
break;
default:
break;
}
}
//下載時長,獲取緩沖時間
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray *array = item.loadedTimeRanges;
//本次緩存的時間
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];
NSTimeInterval totalBufferTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
//這里,獲取的是緩存的總長度,我這里是本地音樂模擬網絡音樂,所以這里totalBufferTime一直就是總時長
NSLog(@"totalBufferTime = %lf", totalBufferTime);
}
}
#pragma mark - Lazy load
- (AVPlayer *)player
{
if (!_player) {
//根據鏈接數組獲取第一個播放的item, 用這個item來初始化AVPlayer
AVPlayerItem *item = [self getItemWithIndex:self.currentIndex];
//初始化AVPlayer
_player = [[AVPlayer alloc] initWithPlayerItem:item];
//監聽播放的進度的方法,addPeriodicTime: ObserverForInterval: usingBlock:
/*
CMTime 每到一定的時間會回調一次,包括開始和結束播放
block回調,用來獲取當前播放時長
return 返回一個觀察對象,當播放完畢時需要,移除這個觀察
*/
__weak typeof(self) weakSelf = self;
self.timeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
float current = CMTimeGetSeconds(time);
NSLog(@"時間 = %lf - duration = %lf", current, CMTimeGetSeconds(item.duration));
if (current) {
weakSelf.progressSlide.value = current / CMTimeGetSeconds(item.duration);
}
}];
}
return _player;
}
- (NSTimer *)timer
{
__weak typeof(self) weakSelf = self;
_timer = [NSTimer timerWithTimeInterval:0.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
weakSelf.animatedView.transform = CGAffineTransformRotate(weakSelf.animatedView.transform, M_PI * 0.1);
}];
return _timer;
}
@end
功能效果
這里聲音就不能給大家展示了,但是可以給大家展示界面,具體可以用代碼自己運行。
下面看輸出結果
2017-12-26 23:38:21.912444+0800 JJMusic_demo2[29647:5084586] 時間 = 0.000000 - duration = nan
2017-12-26 23:38:21.913116+0800 JJMusic_demo2[29647:5084586] 時間 = 0.000000 - duration = nan
2017-12-26 23:38:21.922656+0800 JJMusic_demo2[29647:5084586] 時間 = 0.000000 - duration = nan
2017-12-26 23:38:21.948784+0800 JJMusic_demo2[29647:5084586] totalBufferTime = 249.364898
2017-12-26 23:38:21.951430+0800 JJMusic_demo2[29647:5084586] 準備完畢,可以播放
2017-12-26 23:38:22.110312+0800 JJMusic_demo2[29647:5084586] 時間 = 0.000000 - duration = 249.364898
2017-12-26 23:38:22.110775+0800 JJMusic_demo2[29647:5084586] 時間 = 0.000000 - duration = 249.364898
2017-12-26 23:38:22.608319+0800 JJMusic_demo2[29647:5084586] totalBufferTime = 249.364898
2017-12-26 23:38:23.147871+0800 JJMusic_demo2[29647:5084586] 時間 = 1.001264 - duration = 249.364898
2017-12-26 23:38:24.147846+0800 JJMusic_demo2[29647:5084586] 時間 = 2.001185 - duration = 249.364898
2017-12-26 23:38:25.147776+0800 JJMusic_demo2[29647:5084586] 時間 = 3.001157 - duration = 249.364898
2017-12-26 23:38:26.147997+0800 JJMusic_demo2[29647:5084586] 時間 = 4.001191 - duration = 249.364898
2017-12-26 23:38:27.147628+0800 JJMusic_demo2[29647:5084586] 時間 = 5.001153 - duration = 249.364898
2017-12-26 23:38:28.147630+0800 JJMusic_demo2[29647:5084586] 時間 = 6.001168 - duration = 249.364898
2017-12-26 23:38:29.147603+0800 JJMusic_demo2[29647:5084586] 時間 = 7.001173 - duration = 249.364898
2017-12-26 23:38:30.147581+0800 JJMusic_demo2[29647:5084586] 時間 = 8.001196 - duration = 249.364898
2017-12-26 23:38:31.147527+0800 JJMusic_demo2[29647:5084586] 時間 = 9.001166 - duration = 249.364898
2017-12-26 23:38:32.147437+0800 JJMusic_demo2[29647:5084586] 時間 = 10.001151 - duration = 249.364898
2017-12-26 23:38:33.147451+0800 JJMusic_demo2[29647:5084586] 時間 = 11.001168 - duration = 249.364898
2017-12-26 23:38:34.147956+0800 JJMusic_demo2[29647:5084586] 時間 = 12.001356 - duration = 249.364898
后記
未完,待續~~~