1
votes

I'm trying to use AVPlayer to play audio from external URL (.mp3 files stored in Amazon S3).

I can make the player play and stop the audio perfectly, but when I try to resume it, it starts every time from the start.

My code for play / pause and resume are the following

func playAudio(index: Int) {
    if(self.currentAudioIndex == index) {
      self.resumePlayback()
    }

    self.currentAudioIndex = index;
    let selectedAudio = self.audios[index]
    let url = selectedAudio.url!
    self.playerItem = AVPlayerItem( URL:NSURL( string:url ) )
    self.player = AVPlayer(playerItem:self.playerItem)
    self.player.rate = 1.0;
    self.player.play()
}

func pauseAudio(index: Int) {
    if(self.currentAudioIndex != index) {
      return
    }

    self.playerLastTime = self.player.currentTime()
    self.player.pause()
}

func resumePlayback() {
    let timeScale = self.player.currentItem.asset.duration.timescale;
    let seconds = CMTimeGetSeconds(self.playerLastTime!)
    let time = CMTimeMakeWithSeconds(seconds, timeScale)
    self.player.seekToTime(time, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
    self.player.play()
}

Any help would be greatly appreciated!

1
One thing to note is that if i call the resumePlayback() call at the end of the pauseAudio function IT WORKS... I just can't understand what's wrong herealbertosh
have you tried just ignoring all the custom resuming and just call play again? At least that works for me ;) just have the resumePlayback() call self.player.play()luk2302
One thing to consider is that seeking takes time. There is a seekToTime:toleranceBefore:toleranceAfter:completionHandler: method so that you can start playing after the seeking finishes.matt
@luk2302 Tried that and it's the same thing, maybe it works for you because it's a Local file you are playing?albertosh
@matt Just tried that and it didn't work either :(albertosh

1 Answers

0
votes

Haha! I just found out the answer today, I must have been really tired.

Basically i was missing the return instruction in the if statement inside the play function

if(self.currentAudioIndex == index) {
  self.resumePlayback()
  return //This was missing
}

So what happened was that the audio was being loaded again :)

Cheers,