注意:必须要KVO监听playItem的status,监听AVPlayerStatusReadyToPlay时再调用play方法,不论是远程的还是本地
NSURL *url = [[NSBundle mainBundle] URLForResource:@"rqhhs.mp3" withExtension:nil];
self.playItem = [AVPlayerItem playerItemWithURL:url];// 2.创建AVPlayerItem
self.player = [AVPlayer playerWithPlayerItem:self.playItem];// 3.创建AVPlayer
// self.player.automaticallyWaitsToMinimizeStalling = NO;
self.player.automaticallyWaitsToMinimizeStalling = NO;
[self.playItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
/*
AVPlayerTimeControlStatusPaused,
AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate,
AVPlayerTimeControlStatusPlaying
*/
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
NSLog(@"KVO:未知状态,此时不能播放");
break;
case AVPlayerStatusReadyToPlay:
// self.status = AVPlayerStatusReadyToPlay;
{
if (self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
}
NSLog(@"KVO:准备完毕,可以播放 %ld++++++%@",(long)self.player.timeControlStatus,self.player.reasonForWaitingToPlay);
[self.player play];
}
break;
case AVPlayerStatusFailed:
NSLog(@"KVO:加载失败,网络或者服务器出现问题");
break;
default:
break;
}
}
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray * array = self.playItem.loadedTimeRanges;
CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; //本次缓冲的时间范围
NSTimeInterval totalBuffer = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓冲总长度
NSLog(@"共缓冲%.2f",totalBuffer);
}
}