0

i am trying to implement a slider for AVPlayer to show the length of audio files and allow user to scrub forward and backward.

I've got it working pretty much but when you move the slider knob it reverts back to the original location for a second then skips forward to where you moved it to and starts playing again.

Is there a way to stop this flicking? I'm probably doing something stupid with the code.

This is my block for the slider:

@IBAction func horizontalSliderActioned(_ sender: Any) {

    audioPlayer?.pause()
        //self.timer?.invalidate()

    //create a CMTime the slider value
    let seconds : Int64 = Int64(horizontalSlider.value)
        let preferredTimeScale : Int32 = 1
            let seekTime : CMTime = CMTimeMake(seconds, preferredTimeScale)
                audioPlayerItem?.seek(to: seekTime)

    audioPlayer?.play()
        //self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(PlayerViewController.audioSliderUpdate), userInfo: nil, repeats: true)
}

i am using a timer so i was playing with invalidating and then recreating but it didn't do anything.

This is the timer block:

func audioSliderUpdate() {

    let currentTime : CMTime = (self.audioPlayerItem?.currentTime())!
    let seconds : Float64 = CMTimeGetSeconds(currentTime)
    let time : Float = Float(seconds)

    self.horizontalSlider.value = time


}

which is called by the timer, where the audio starts playing:

self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(PlayerViewController.audioSliderUpdate), userInfo: nil, repeats: true)

maximum time is set from duration where the audio is played:

  let duration : CMTime = (self.audioPlayer?.currentItem!.asset.duration)!
  let seconds : Float64 = CMTimeGetSeconds(duration)
  let maxTime : Float = Float(seconds)

  self.horizontalSlider.maximumValue = maxTime
Pippo
  • 1,439
  • 1
  • 18
  • 35

1 Answers1

0

I think range of your slider is not set to the range that can be achieved by assigning time to it.

The defaults are set like this:enter image description here

You need to set them to 0...length of the played sound or enter the time in relative units 0...1, if you didn't already.

MirekE
  • 11,515
  • 5
  • 35
  • 28