Search code examples
iosavaudioengine

AVAudioEngine seek the time of the song


I am playing a song using AVAudioPlayerNode and I am trying to control its time using a UISlider but I can't figure it out how to seek the time using AVAUdioEngine.


Solution

  • After MUCH trial and error I think I have finally figured this out.

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

    let nodeTime: AVAudioTime  = self.playerNode.lastRenderTime
    let playerTime: AVAudioTime = self.playerNode.playerTimeForNodeTime(nodeTime)
    let sampleRate = playerTime.sampleRate
    

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

    let 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:

    let length = Float(songDuration!) - Slider.value
    let framesToPlay = AVAudioFrameCount(Float(playerTime.sampleRate) * length)
    

    Finally, stop your node, schedule the new segment of audio, and start your node again!

    playerNode.stop()
    
    if framestoplay > 1000 {
       playerNode.scheduleSegment(audioFile, startingFrame: newSampleTime, frameCount: framesToPlay, atTime: nil,completionHandler: nil)
    }
            
    playerNode.play()
    

    If you need further explanation I wrote a short tutorial here: http://swiftexplained.com/?p=9