我有以下代码:
AVPlayerItem *currentItem = [AVPlayerItem playerItemWithURL:soundURL];
[self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
[self.audioPlayer play];
其中soundURL
是remoteURL
。它工作正常。 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];
}
任何人都可以帮我解决这个问题吗?
答案 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];
}];
}
}
}