简体   繁体   English

AVPlayer与iOS中的UISlider同步

[英]AVPlayer synchronised with UISlider in iOS

Working on an app in iOS , I am playing a video using AVPlayer and i am synchronising the slider with the playerItem current duration using: 在iOS中的应用程序上工作,我正在使用AVPlayer播放视频,并使用以下命令将滑块与playerItem当前持续时间同步:

//synchronizing the current time label and slider with the player.
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 100) queue:dispatch_get_main_queue() usingBlock:^(CMTime time)

{
    CMTime endTime = CMTimeConvertScale (self.player.currentItem.asset.duration, self.player.currentTime.timescale, kCMTimeRoundingMethod_RoundHalfAwayFromZero);
    if (CMTimeCompare(endTime, kCMTimeZero) != 0) {
        double normalizedTime = (double) self.player.currentTime.value / (double) endTime.value;
        self.slider.value = normalizedTime;
    }
    Float64 currentSeconds = CMTimeGetSeconds(self.player.currentTime);
    int mins = currentSeconds/60.0;
    int secs = fmodf(currentSeconds, 60.0);
    NSString *minsString = mins < 10 ? [NSString stringWithFormat:@"0%d", mins] : [NSString stringWithFormat:@"%d", mins];
    NSString *secsString = secs < 10 ? [NSString stringWithFormat:@"0%d", secs] : [NSString stringWithFormat:@"%d", secs];
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%@:%@", minsString, secsString];
}];

The problem is that i am playing the video in Modal view, when I press the button to dismiss the view controller, the view controller dismisses but the video keep on playing in the background(as the audio of the asset can be heard). 问题是我在“模态”视图中播放视频,当我按下按钮以关闭视图控制器时,视图控制器关闭,但视频继续在后台播放(因为可以听到资产的音频)。 How can i solve that? 我该如何解决? I am sure that it has to do with the queue I am using, but i have tried both the main queue and the concurrent queue, but every time, results are same. 我确定这与我正在使用的队列有关,但是我已经尝试了主队列和并发队列,但是每次结果都是相同的。

I think you need to stop AVAssetReader by calling cancelReading method on it. 我认为您需要通过在其上调用cancelReading方法来停止AVAssetReader

Doc: 文件:

cancelReading 取消阅读

Cancels any background work and prevents the receiver's outputs from reading more samples. 取消任何后台工作,并防止接收器的输出读取更多样本。

  • (void)cancelReading Discussion If you want to stop reading samples from the receiver before reaching the end of its time range, you should call this method to stop any background read ahead operations that the may have been in progress. (void)cancelReading讨论如果要在到达接收器的时间范围结束之前停止从接收器读取样本,则应调用此方法以停止可能正在进行的任何后台预读操作。

Also you should use removeTimeObserver method of AVPlayer when you dismiss modal view. 关闭模态视图时,也应使用AVPlayer removeTimeObserver方法。

There is also pause method of AVPlayer if you don't have AVAssetReader . 如果您没有AVAssetReader则还有AVPlayer的pause方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM