0

I have a UISlider and AvAudioPlayer, currently I am able to set the UISlider to the currentTime of a AvAudioPlayer like so:

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

@objc func updateTimer() {
    if(audio != nil) {
       audioSlider.setValue(Float((self.audio?.currentTime)! / (self.audio?.duration)!), animated: false)
    }
}

But how would I set the currentTime of the AVAudioPlayer when changing the value of the UISlider?

@IBAction func audioSliderUpdated(_ sender: Any) {
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
user979331
  • 11,039
  • 73
  • 223
  • 418
  • see this for e.g : https://stackoverflow.com/questions/43062870/add-custom-controls-to-avplayer-in-swift/43070099#43070099 – Anbu.Karthik Jul 10 '18 at 04:35

3 Answers3

2

You can use the currentTime property of AVAudioPlayer:

@IBAction func audioSliderUpdated(_ sender: Any) {
  if let slider = sender as? UISlider {
    self.audio?.currentTime = slider.value    
  }
}
Christian Abella
  • 5,747
  • 2
  • 30
  • 42
1

Use this, slider value changes according to time

 @IBAction func slide(_ sender: UISlider) {
    self.audio.currentTime = TimeInterval(slider.value)
}
chandra1234
  • 357
  • 6
  • 15
0

You have to convert your slider value to a new value which based on your media file.

First, you must config your slider values to work in normalized values (from 0.0 to 1.0)

/// call this on viewDidLoad: configDefaults(for: audioSlider)
func configDefaults(for slider: UISlider)
    slider.minimumValue = 0.0
    slider.maximumValue = 1.0
}

Then you should calculate currentTime from audioSlider.value and duration then set it to the player.currentTime.

@IBAction func audioSliderUpdated(_ sender: Any) {
    guard let slider = sender as? UISlider,
        let player = audio else {
        return
    }
    player.currentTime = Double(slider.value) * player.duration
}
ngbaanh
  • 440
  • 2
  • 12