iOS实现播放远程网络音乐的核心技术点总结

2020-01-18 17:23:06王振洲


//KVO监听音乐缓冲状态
[self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];

loadedTimeRanges属性发生改变时,回调如下:


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
  if ([keyPath isEqualToString:@"loadedTimeRanges"]) {

    NSArray * timeRanges = self.player.currentItem.loadedTimeRanges;
    //本次缓冲的时间范围
    CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];
    //缓冲总长度
    NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
    //音乐的总时间
    NSTimeInterval duration = CMTimeGetSeconds(self.player.currentItem.duration);
    //计算缓冲百分比例
    NSTimeInterval scale = totalLoadTime/duration;
    //更新缓冲进度条
    self.loadTimeProgress.progress = scale;
  }

}

loadedTimeRanges这个属性是一个数组,里面装的是本次缓冲的时间范围,这个范围是用一个结构体 CMTimeRange表示,当然在oc中结构体是不能直接存放数组的,所以它被包装成了oc对象 NSValue

我们来看下这个结构体:


typedef struct
{
  CMTime      start;    
  CMTime      duration;  
} CMTimeRange;

start表示本次缓冲时间的起点,duratin表示本次缓冲持续的时间范围,具体详细的计算方法可以看上面方法的实现。

当音乐播放完成,或者切换下一首歌曲时,请务必记得移除观察者,否则会crash。操作如下:


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

6、监听音乐播放的进度

这个不是通过KVO了,AVPlayer专门提供了下面这个api用来监听播放的进度:


/**
 监听音乐播放进度

 @param interval 监听的时间间隔,用来设置多长时间回调一次
 @param queue  队列,一般传主队列
 @param block  回调的block,会把当前的播放时间传递过来

 @return 监听的对象
 */
- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;