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;
- 1.官方給出公式 :value / timescale = seconds 其中value是視頻的總幀數(shù) timescale:視頻幀率(幀/s)
AVPlayerItem的Duration屬性就是一個CMTime類型的數(shù)據(jù)具伍。所以獲取視頻的總時長(秒)需要duration.value/duration.timeScale - 系統(tǒng)也給出一個方法 直接獲取視頻CMTimeGetSeconds(CMTime time) 腹缩,當然這個方法最終也是根據(jù)參數(shù)time.value / time.timescale 來計算時長,此時參數(shù)是整個視頻的返回的就是整個視頻的時長渴丸,如果參數(shù)time只是一部分視頻那么返回就是這部分視頻時長桑驱。
/*!
@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);
刷新播放進度和狀態(tài)
實時更新當前播放時間狀態(tài),AVPlayer已經(jīng)提供了方法:
addPeriodicTimeObserverForInterval: queue: usingBlock。當播放進度改變的時候方法中的回調會被執(zhí)行袱箱。我們可以在這里做刷新時間的操作
__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) {
}];
}
}