7

我有以下代码:

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];
}

谁能帮我解决这个问题?

4

2 回答 2

8

我建议做几件事。首先,获取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];
               }];
}
于 2014-02-24T16:17:41.833 回答
1

我正在使用下面的代码进行拖动completionHandler-在@Corey 的回答之后添加,它在没有任何网络服务依赖的情况下工作得很好:

- (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];
            }];
        }
    }
}
于 2015-09-02T06:53:47.380 回答