I'm making a simple audio player app, and it allows a user to change where they are in a track using the UISlider.
What it doesn't do: the slider doesn't update based on the track's progress. I found a similar question here, and the second answer was responsive to AVAudioPlayer
-- suggesting using currentTime
to update the slider. I want to try to do that.
Here's my code:
import UIKit
import AVFoundation
class MusicViewController: UIViewController {
....
@IBOutlet var Slider: UISlider!
@IBAction func changeAudioTime(_ sender: Any) {
Slider.maximumValue = Float(audioPlayer.duration)
audioPlayer.stop()
audioPlayer.currentTime = TimeInterval(Slider.value)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
func updateSlider(){
Slider.value = Float(audioPlayer.currentTime)
print("Changing works")
}
The first function works fine -- the user can change where they are. However, the second function to me should change the Slider.value
based on the currentTime
of the AudioPlayer. It doesn't do that.
It's also not printing, so my belief is it isn't firing.
I'm new to Swift so I am likely missing something. Any ideas?
Tested code:-
Add timer variable
var timer: Timer?
in a function where you start playing your audio:
slidderrr.value = 0.0
slidderrr.maximumValue = Float((player?.duration)!)
audioPlayer.play()
timer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
Don't forget to invalidate timer when you don't want to update slider
func stopPlayer() {
player?.stop()
timer?.invalidate()
print("Player and timer stopped")
}