3

enter image description hereI'm using AVPlayer to stream audio from a server and what I want to do now is to show a custom UISlider who shows the progress of the buffering.

Anyone come up with this? Please give me solution. Now player load whole duration in once and show in UISlider.

iHarshad
  • 143
  • 11

1 Answers1

0

you need to use preferredforwardbufferduration

This property defines the preferred forward buffer duration in seconds. If set to 0, the player will choose an appropriate level of buffering for most use cases. Setting this property to a low value will increase the chance that playback will stall and re-buffer, while setting it to a high value will increase demand on system resources.

also check here for detailed example of how to use : Is it possible to pause and resume buffering of AVPlayer?

inside your player you need to observe time range using below function

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)

like this:

            let timeRanges = change![NSKeyValueChangeKey.newKey] as? NSArray
        if timeRanges != nil && timeRanges!.count != 0 {
            DispatchQueue.main.async {
                let cmTimeRange = (timeRanges![0] as AnyObject).timeRangeValue as CMTimeRange
                self.playerView.timeSlider.bufferValue = Float(CMTimeGetSeconds(cmTimeRange.start) + CMTimeGetSeconds(cmTimeRange.duration))
            }
        }

I have a custom slider with a variable I defined as bufferValue you can override func draw(_ rect: CGRect)inside your slider and apply changes while buffer is progressing.

I get draw to call anytime bufferValue changes by calling self.setNeedsDisplay()inside didSet

    @IBInspectable var bufferValue : Float = 0 {
    didSet {
        if(bufferValue < 0 ) {
            bufferValue = 0
        } else if (bufferValue > maximumValue) {
            bufferValue = maximumValue
        }
        self.setNeedsDisplay()
    }
}
MohyG
  • 1,335
  • 13
  • 25