addPeriodicTimeObserverForInterval called extra time

老子叫甜甜 提交于 2019-12-12 11:23:06

问题


I have a AVPlayer with 4 sec video (NSTimeInterval duration = CMTimeGetSeconds(self.playerItem.asset.duration) = 4).

I'd like to update UI with changes:

self.periodicTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

    [weakSelf currentTimeDidChange:CMTimeGetSeconds(time)];

}];

But for some reasons I get extra calls to UI:

- (void)currentTimeDidChange:(NSTimeInterval)currentTime {
    NSLog(@"timePassed %f, total: %f", currentTime, self.duration);
}

Logs:

2015-07-23 13:47:07.412   timePassed 0.000000, total: 4.000000
2015-07-23 13:47:07.448   timePassed 0.002814, total: 4.000000
2015-07-23 13:47:07.450   timePassed 0.005481, total: 4.000000
2015-07-23 13:47:08.447   timePassed 1.001473, total: 4.000000
2015-07-23 13:47:09.446   timePassed 2.001612, total: 4.000000
2015-07-23 13:47:10.446   timePassed 3.002021, total: 4.000000
2015-07-23 13:47:11.446   timePassed 4.002139, total: 4.000000
2015-07-23 13:47:12.445   timePassed 5.001977, total: 4.000000
2015-07-23 13:47:12.492   timePassed 5.046618, total: 4.000000

Any help is appreciated


回答1:


you need to be sure that you are not calling periodicTimeObserver many time so do this write this code

if (self.periodicTimeObserver == nil){
self.periodicTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

    [weakSelf currentTimeDidChange:CMTimeGetSeconds(time)];

}];
}

then as soon as your video is finishes playing remove observer

[player removeTimeObserver:self.periodicTimeObserver];
self.periodicTimeObserver = nil;



回答2:


I got inconsistencies too. So I'm not relying on the value given by the block but on the value from the playerItem itself:

self.periodicTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:nil usingBlock:^(__unused CMTime time) {
    [weakSelf currentTimeDidChange:CMTimeGetSeconds(self.playerItem.currentTime)];
}];


来源:https://stackoverflow.com/questions/31588482/addperiodictimeobserverforinterval-called-extra-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!