1

I am trying to control the audio with the UISlider, the print() statement prints the correct value and the app doesn't crash, however when I try to grab it and move the slider (the thumb tint), the UISlider doesn't slide but just moves a bit when I try to slide it ( like a tap ). When I comment the 6th row the slider response correctly (But of course nothing happens).

var playerItem : AVPlayerItem?
var player : AVPlayer?    
@IBAction func adjustSongProgress(_ sender: UISlider) {
    player?.pause()
    let floatTime = Float(CMTimeGetSeconds(player!.currentTime()))
    sliderProgressOutlet.value = floatTime
    print(floatTime)
    player?.play()
}
Zankrut Parmar
  • 1,872
  • 1
  • 13
  • 28
Vadim F.
  • 881
  • 9
  • 21
  • see this for sample : https://stackoverflow.com/questions/43062870/add-custom-controls-to-avplayer-in-swift/43070099#43070099 – Anbu.Karthik Feb 15 '19 at 10:09

2 Answers2

1

 Fixed it by deleting AVPlayer and changing AVPlayerItem to AVAudioPlayer, then putting the song URL into data : `

    //DOWNLOADS THE SONG IN THE URL AND PUTS IT IN DATA
    var task: URLSessionTask? = nil

    if let songUrl = songUrl {
        task = URLSession.shared.dataTask(with: songUrl, completionHandler: { data, response, error in
            // SELF.PLAYER IS STRONG PROPERTY
            if let data = data {
                self.playerItem = try? AVAudioPlayer(data: data)
                self.playPause()
                DispatchQueue.main.async {
                    self.sliderProgress()
                }
            }
        })
        task?.resume()`

Then I changed UISlider IBAction Value Changed to Touch Down and Touch Up Inside when I connected it to the ViewController:

    // TOUCH DOWN
@IBAction func SliderTouchDown(_ sender: UISlider) {
    playerItem?.pause()
}

//TOUCH UP INSIDE
@IBAction func SliderTouchUpInside(_ sender: UISlider) {
    playerItem?.currentTime = TimeInterval(sliderProgressOutlet.value)
    playerItem?.play()
}
Vadim F.
  • 881
  • 9
  • 21
0

iOS Slider takes value between 0 to 1. if CMTimeGetSeconds return value outside from 0 to 1 it will not set properly.

therefor you have to convert your Time range to slider range.

for ex : your video/audio length is 120 second and you want to move slider to 30 second.than you can calculate new value using below function.

OldRange = (OldMax - OldMin)
NewRange = NewMax - NewMin

NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

oldRange = 120 - 0
newRange = 1 - 0
New value = (30-0)*1/120+0 = 0.25
Bhavesh.iosDev
  • 924
  • 9
  • 27
  • I am changing the maximum value of the slider to the length of the song : 'let songDuration = Float(CMTimeGetSeconds(((playerItem!.duration)))) sliderProgressOutlet.maximumValue = songDuration' – Vadim F. Feb 16 '19 at 19:35
  • I think you want to forward/backword song progress according to slider right? – Bhavesh.iosDev Feb 17 '19 at 04:37