宽容他人,放过自己。

AVPlayer网络音频的播放

Posted on By anchoriteFili

AVPalyer音频播放.zip

AVAudioPlayer支持本地播放,不支持网络播放,所以用AVPlayer进行网络音频播放

在appdelegate中添加下面代码才能够手机扬声器播放

#pragma mark 录音点击下事件
AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&setCategoryError];
    
    if(setCategoryError){
        NSLog(@"%@", [setCategoryError description]);
    }

#pragma mark 录音结束事件
AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *setCategoryError = nil;
    [session setCategory:AVAudioSessionCategorySoloAmbient error:&setCategoryError];
    
    if(setCategoryError){
        NSLog(@"%@", [setCategoryError description]);
    }

快捷创建一个简单的音频播放

#pragma mark 创建播放器
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[self.itemsArray objectAtIndex:0]];
self.player = [[AVPlayer alloc] initWithPlayerItem:item];
[self.player play];

模板网络代码

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UISlider *sliderProgress; //进度条

@property (weak, nonatomic) IBOutlet UIProgressView *huanCunProgressView; //缓存条的显示

@property (weak, nonatomic) IBOutlet UIButton *playButton; //播放按钮

@property (nonatomic,assign) int itemIndex; //当前播放的音乐位置

@property (nonatomic,assign) BOOL isPlaying; //判断是否是播放状态

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self.playButton setEnabled:NO]; //没有准备好不能点击
    [self.playButton setTitle:@"准备中" forState:UIControlStateNormal];
    
    self.isPlaying = NO; //初始状态没有播放
    
#pragma mark 将音乐连接存储在数组中
    NSURL *url = [NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"];
    NSURL *url1 = [NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"];
    NSURL *url2 = [NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"];
    NSURL *url3 = [NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"];
    NSURL *url4 = [NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"];
    
    self.itemArray = @[url,url1,url2,url3,url4];
    
#pragma mark 创建播放器
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[self.itemArray objectAtIndex:0]];
    self.player = [[AVPlayer alloc] initWithPlayerItem:item];
    [self.player play];
    
#pragma mark 注册播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
#pragma mark 添加观察者,用来监视播放器的状态的变化
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
#pragma mark 更新时间显示标签
    __weak ViewController *weakVC = self;
    __weak AVPlayer *weakPlayer = self.player;
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
#pragma mark 获取当前播放时间
        float currentTime = weakPlayer.currentItem.currentTime.value/weakPlayer.currentItem.currentTime.timescale;
        NSLog(@"currentTime = %f",currentTime);
        
#pragma mark 获取缓存时间
        NSTimeInterval timeInterval = [weakVC availableDuration];
        NSLog(@"time Interval : %f",timeInterval);
        
#pragma mark 获取总时间长
        CMTime duration = weakPlayer.currentItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        weakVC.sliderProgress.value = currentTime/totalDuration; //播放进度条
        [weakVC.huanCunProgressView setProgress:timeInterval/totalDuration animated:YES]; //缓存进度条
    }];
}

#pragma mark 观察播放器状态的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    //当状态status变为准备就绪时,播放按钮可以点击
    if ([keyPath isEqualToString:@"status"]) {
        if (self.player.status == AVPlayerStatusReadyToPlay) {
            [self.playButton setEnabled:YES]; //开启播放按钮
            [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
        }
    }
}

#pragma mark 拖动slider,快进快退
- (IBAction)changeProgress:(UISlider *)sender {
    
#pragma mark 获取总时间长
    CMTime duration = self.player.currentItem.duration;
    CGFloat totalDuration = CMTimeGetSeconds(duration);
#pragma mark 根据总时长来获得当前
    [self.player seekToTime:CMTimeMake(self.sliderProgress.value*totalDuration, 1)];
}

#pragma mark 上一首点击事件
- (IBAction)upBtnClik:(UIButton *)sender {
    
    if (self.itemIndex-1 >= 0) {
        AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[self.itemArray objectAtIndex:self.itemIndex-1]];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [self.player play];
        self.itemIndex --;
    }
    
}

#pragma mark 下一首点击事件
- (IBAction)downBtnClick:(UIButton *)sender {
    
    if (self.itemIndex+1 < self.itemArray.count) {
        AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[self.itemArray objectAtIndex:self.itemIndex+1]];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [self.player play];
        self.itemIndex ++;
    }
}

#pragma mark 播放按钮点击事件
- (IBAction)play:(UIButton *)sender {
    
    if (self.isPlaying) {
        
        [self.player pause];
        self.isPlaying = NO;
        [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
    } else {
        
        [self.player play];
        self.isPlaying = YES;
        [self.playButton setTitle:@"暂停" forState:UIControlStateNormal];
        
        //获取当前播放视频的总时长
//        self.sliderProgress.maximumValue = self.player.currentItem.duration.value/self.player.currentItem.duration.timescale;
    }
}


#pragma mark 播放结束后的事件
- (void)playDidEnd {
    
    NSLog(@"播放完毕");
}

#pragma mark 更新缓冲进度方法
- (NSTimeInterval)availableDuration {
    
    NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue]; //获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    
    NSTimeInterval result = startSeconds + durationSeconds; //计算缓冲进度
    
    return result;
}


#pragma mark 播放器懒加载
- (AVAudioPlayer *)audioPlayer {
    
    if (!_audioPlayer) {
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://ac-l9kxeopp.clouddn.com/Z8OIyYPogawR2D35SNXcBDD.mp3"] error:nil];
    }
    return _audioPlayer;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end