Search code examples
iosobjective-cavplayeruiprogressbar

AVPlayer seekToTime: backward not working


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?


Solution

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