Changing Playback Time (Seeking) using AVAudioEngine

For those of you that like harnessing the power of Apple’s fairly new AVAudioEngine, here is a quick tutorial explaining how to change the playback of an audiofile by using a Slider (also known as seeking).

This tutorial assumes you already have a background with AVAudioEngine and have a working example that can playback a file.

First, you need to calculate the sample rate of your file. To do this get the last render time of your AudioNode:

var nodetime: AVAudioTime  = self.playerNode.lastRenderTime
var playerTime: AVAudioTime = self.playerNode.playerTimeForNodeTime(nodetime)
var sampleRate = playerTime.sampleRate

Then, multiply your sample rate by the new time the user has scrolled to in seconds. This will give you the exact frame of the song at which you want to start the player:

var newsampletime = AVAudioFramePosition(sampleRate * Double(Slider.value))

Next, you are going to want to calculate the amount of frames there are left in the audio file:

var length = Float(songDuration!) - Slider.value
var framestoplay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)

Great! we have all the pieces we need to jump to our new time. Finally, stop your node, schedule the new segment of audio, and start your node again!


if framestoplay > 100 {
   playerNode.scheduleSegment(audioFile, startingFrame: newsampletime, frameCount: framestoplay, atTime: nil,completionHandler: nil)


Note that we do not schedule playback if the remaining frames in the file are less than 100. This is where you would recognize the end of the audiofile and change to a new one or restart the file.



  1. Hi! Thank you! This was really helpful. I was struggling with this for some time. Do you have any idea how I can schedule the end of a song so that it will play only until that time? Thank you again!

  2. Glad I could help Lucian! What I did was implement my own timer that after every second adds to a variable which is compared to the song length every second. Then when the variable is equal to or greater than the song length you play the next song.

  3. Thanks for this, it’s saved me a lot of time. Just wanted to add that you can get the sample rate from AVAudioFile.processingFormat (an AVAudioFormat class), and the length from AVAudioFile.length

  4. Hello!
    May I ask what the max value is for the Slider? Is it the duration of the song in seconds? Also, how did you obtain the variable “songDuration”? Is songDuration equal to the maximum value of the slider?

    Thank you in advance!!

  5. Hi i have issue with this i got playertime =0 while moving slider could pls help me regarding this

Leave a Reply

Your email address will not be published. Required fields are marked *