I have the following code:
AVPlayerItem *currentItem = [AVPlayerItem playerItemWithURL:soundURL];
[self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
[self.audioPlayer play];
where soundURL
is a remoteURL
. It works fine. The AVPlayer
plays the music perfectly. I have a progress bar and i am updating it based on the current time of the player.
Everything works fine. My issue is when i drag the progress bar forward the audioplayer
starts from the new location but if i drag the progressbar
it doesn't start from the new location in fact it resumes from the previous location. Here is my progress bar drag start and stop code:
- (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];
}
Can anyone help me fix this issue?
I suggest doing a couple of things. First, get the timescale
value and pass it to the CMTime
struct. Second, use the seekToTime:toleranceBefore:toleranceAfter:completionHandler:
method for more accurate seeking. For example, your code would look like:
- (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];
}];
}
I am using below code for dragging- Added completionHandler
after @Corey's answer and it works great without any web-service dependency:
- (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];
}];
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With