AVPlayer seekToTime:向后不工作

时间:2014-02-24 15:56:07

标签: ios objective-c avplayer uiprogressbar

我有以下代码:

AVPlayerItem *currentItem = [AVPlayerItem playerItemWithURL:soundURL];
[self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
[self.audioPlayer play];

其中soundURLremoteURL。它工作正常。 AVPlayer完美播放音乐。我有一个进度条,我根据播放器的当前时间更新它。

一切正常。我的问题是当我向前拖动进度条时,audioplayer从新位置开始,但如果我拖动progressbar它不会从新位置开始,实际上它从之前的位置恢复。这是我的进度条拖动开始和停止代码:

- (IBAction)progressBarDraggingStart:(id)sender
{
     if (self.audioPlayer.rate != 0.0)
     {
          [self.audioPlayer pause];
     }
}

- (IBAction)progressBarDraggindStop:(id)sender
{
     CMTime newTime = CMTimeMakeWithSeconds(self.progressBar.value, 1);
     [self.audioPlayer seekToTime:newTime];
     [self.audioPlayer play];
}

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:7)

我建议你做几件事。首先,获取timescale值并将其传递给CMTime结构。其次,使用seekToTime:toleranceBefore:toleranceAfter:completionHandler:方法进行更准确的搜索。例如,您的代码如下所示:

- (IBAction)progressBarDraggindStop:(id)sender {
    int32_t timeScale = self.audioPlayer.currentItem.asset.duration.timescale;

    [self.audioPlayer seekToTime: CMTimeMakeWithSeconds(self.progressBar.value, timeScale)
                 toleranceBefore: kCMTimeZero
                  toleranceAfter: kCMTimeZero
               completionHandler: ^(BOOL finished) {
                   [self.audioPlayer play];
               }];
}

答案 1 :(得分:1)

我正在使用以下代码进行拖动 - 在@ Corey的回答之后添加了completionHandler并且它在没有任何Web服务依赖性的情况下运行良好:

- (void) sliderValueChanged:(id)sender {
    if ([sender isKindOfClass:[UISlider class]]) {
        UISlider *slider = sender;

        CMTime playerDuration = self.avPlayer.currentItem.duration;
        if (CMTIME_IS_INVALID(playerDuration)) {
            return;
        }

        double duration = CMTimeGetSeconds(playerDuration);
        if (isfinite(duration)) {
            float minValue = [slider minimumValue];
            float maxValue = [slider maximumValue];
            float value = [slider value];

            double time = duration * (value - minValue) / (maxValue - minValue);

            [self.avPlayer seekToTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
                [self.avPlayer play];
            }];
        }
    }
}