AVPlayer的使用

本文可以解决缓冲和播放会暂停的问题
在iOS开发中,播放视频通常有两种方式,一种是使用MPMoviePlayerController(需要导入MediaPlayer.Framework),还有一种是使用AVPlayer。关于这两个类的区别可以参考http://stackoverflow.com/questions/8146942/avplayer-and-mpmovieplayercontroller-differences,)
简而言之就是MPMoviePlayerController使用更简单,功能不如AVPlayer强大,而AVPlayer使用稍微麻烦点,不过功能更加强大。这篇博客主要介绍下AVPlayer的基本使用,由于 我也是刚刚接触,所以有问题大家直接指出~
监听playerItem的status和loadedTimeRange属性,status有三种状态:
AVPlayerStatusUnknown,

AVPlayerStatusReadyToPlay,

AVPlayerStatusFailed

当status等于AVPlayerStatusReadyToPlay时代表视频已经可以播放了,我们就可以调用play方法播放了。

loadedTimeRange属性代表已经缓冲的进度,监听此属性可以在UI中更新缓冲进度,也是很有用的一个属性。

最后添加一个通知,用于监听视频是否已经播放完毕,然后实现KVO的方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
 {
     AVPlayerItem *playerItem = (AVPlayerItem *)object; 
     if ([keyPath isEqualToString:@"status"]) {
          if ([playerItem status] ==AVPlayerStatusReadyToPlay) {    
    NSLog(@"AVPlayerStatusReadyToPlay"); 
    self.stateButton.enabled = YES; 
    CMTime duration = self.playerItem.duration;// 获取视频总长度 
    CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒 
    _totalTime = [self convertTime:totalSecond];// 转换成播放时间
    [self customVideoSlider:duration];// [自定义]UISlider外观 
    NSLog(@"movie totalduration:%f",CMTimeGetSeconds(duration));
    [self monitoringPlayback:self.playerItem];// 监听播放状态
  } else if ([playerItem status] == AVPlayerStatusFailed) { 
    NSLog(@"AVPlayerStatusFailed"); 
} 
  } else if ([keyPath isEqualToString:@"loadedTimeRanges"])  { 
    NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
    NSLog(@"Time Interval:%f",timeInterval);
    CMTime duration = self.playerItem.duration; 
    CGFloat totalDuration = CMTimeGetSeconds(duration);
    [self.videoProgress setProgress:timeInterval / totalDuration animated:YES]; 
}}

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

- (NSString *)convertTime:(CGFloat)second{ NSDate *d = [NSDate dateWithTimeIntervalSince1970:second]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    if (second/3600 >= 1) { [formatter setDateFormat:@"HH:mm:ss"]; 
} else {
  [formatter setDateFormat:@"mm:ss"]; 
} 
   NSString *showtimeNew = [formatter stringFromDate:d]; 
   return showtimeNew;
}

你可能感兴趣的:(AVPlayer的使用)