0

I'm working on a music player in Swift. The user can play a track, pause the track, or move a slider to choose a place to start. These three functions work.

However, if a user plays a track, listens for 1:00, and hits pause: when they click play again, it will restart the track from 0:00 instead of respecting where they paused.

I am using AVAudioPlayer as a media player -- according to the documentation, .play() allows you to specify a start-point using atTime.

So I tried to use atTime and have it start where the slider is -- if a listener listens for 1:00, I want atTime to dynamically pick that up. I try to establish this time value in a var.

class MusicViewController: UIViewController {
// removed imports and viewdidload to condense

    @IBAction func playDownload(_ sender: Any) { 
    // removed file download code to condense

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: destinationUrl)
            guard let player = audioPlayer else { return }

            //here's where I try to capture a time value from the slider's progress
            let checkTime = TimeInterval(Slider.value)

            player.prepareToPlay()
            player.play(atTime: checkTime)
        } catch let error {
            print(error.localizedDescription)
        }

        // updates slider with progress
        Slider.value = 0.0
        Slider.maximumValue = Float((audioPlayer?.duration)!)
        audioPlayer.play()
        timer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(self.updateSlider), userInfo: nil, repeats: true)
    }

    @IBAction func pause(_ sender: Any) {

        if audioPlayer.isPlaying {
            audioPlayer.pause()
        } else {
            audioPlayer.play()
        }
    }
    @IBOutlet var Slider: UISlider!

    @objc func updateSlider() {

        Slider.value = Float(audioPlayer.currentTime)
        print("Changing works")
    }
}

So I am trying to capture progress and have .play respect that -- this code will run, but it does not work. No errors but after hitting play, it will go to the end of the track immediately now. No good.

I am new to Swift - any idea where I went wrong?

Jay Patel
  • 2,642
  • 2
  • 18
  • 40
darkginger
  • 652
  • 1
  • 10
  • 38
  • once you paused the avplayer just invalidate the time and once you start the play resume the timer – Anbu.Karthik Jan 11 '18 at 04:47
  • hey, I tried that and changed the pause function to the following but it still goes to the end of the file when I hit play -- testing right now to see if I can find out what isn't working. ` @IBAction func pause(_ sender: Any) { if audioPlayer.isPlaying{ audioPlayer.pause() timer?.invalidate() }else{ audioPlayer.play() } }` – darkginger Jan 11 '18 at 05:58
  • see this one may be it will help you https://stackoverflow.com/questions/43062870/add-custom-controls-to-avplayer-in-swift/43070099#43070099 – Anbu.Karthik Jan 11 '18 at 06:00

0 Answers0