AVPlayer

2019-04-04  本文已影响0人  JopYin
iOS_player.png

获取视频的总时长

typedef struct
{
    CMTimeValue value;      /*! @field value The value of the CMTime. value/timescale = seconds. */
    CMTimeScale timescale;  /*! @field timescale The timescale of the CMTime. value/timescale = seconds.  */
    CMTimeFlags flags;      /*! @field flags The flags, eg. kCMTimeFlags_Valid, kCMTimeFlags_PositiveInfinity, etc. */
    CMTimeEpoch epoch;      /*! @field epoch Differentiates between equal timestamps that are actually different because
                                                 of looping, multi-item sequencing, etc.  
                                                 Will be used during comparison: greater epochs happen after lesser ones. 
                                                 Additions/subtraction is only possible within a single epoch,
                                                 however, since epoch length may be unknown/variable. */
} CMTime;
/*!
    @function   CMTimeGetSeconds
    @abstract   Converts a CMTime to seconds.
    @discussion If the CMTime is invalid or indefinite, NAN is returned.  If the CMTime is infinite, +/- __inf()
                is returned.  If the CMTime is numeric, epoch is ignored, and time.value / time.timescale is
                returned.  The division is done in Float64, so the fraction is not lost in the returned result.
    @result     The resulting Float64 number of seconds.
*/
CM_EXPORT 
Float64 CMTimeGetSeconds(
                CMTime time)
                            __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);

刷新播放进度和状态

实时更新当前播放时间状态,AVPlayer已经提供了方法:
addPeriodicTimeObserverForInterval: queue: usingBlock。当播放进度改变的时候方法中的回调会被执行。我们可以在这里做刷新时间的操作

 __weak __typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //当前播放的时间
        NSTimeInterval currentTime = CMTimeGetSeconds(time);
        //视频的总时间
        NSTimeInterval totalTime = CMTimeGetSeconds(weakSelf.player.currentItem.duration);
        //设置滑块的当前进度
        weakSelf.sliderView.value = currentTime/totalTime;
        //设置显示的时间:以00:00:00的格式
        weakSelf.currentPlayTimeLabel.text = [weakSelf formatTimeWithTimeInterVal:currentTime];
    }];

快进或者快退到指定时间点播放

AVPlayer实例调用

- (void)seekToTime:(CMTime)time completionHandler:(void (^)(BOOL finished))completionHandler NS_AVAILABLE(10_7, 5_0);
//UISlider的响应方法:拖动滑块,改变播放进度
- (IBAction)sliderViewChange:(id)sender {
    if(self.player.status == AVPlayerStatusReadyToPlay){
        NSTimeInterval playTime = self.sliderView.value * CMTimeGetSeconds(self.player.currentItem.duration);
        CMTime seekTime = CMTimeMake(playTime, 1);
        [self.player seekToTime:seekTime completionHandler:^(BOOL finished) {
        }];
    }
}
上一篇下一篇

猜你喜欢

热点阅读