Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show AVplayer current play duration in UISlider

I am using a custom UISlider to implement the scrubbing while playing a video in AVPlayer. Trying to figure out the best way to show the current play time and the remaining duration on the respective ends of the UISlider as it usually is shown in MPMoviePlayerController.

Any help is appreciated.

like image 327
Soumya Das Avatar asked Oct 25 '11 19:10

Soumya Das


2 Answers

Swift 4.x

let player = AVPlayer()
player.addPeriodicTimeObserver(forInterval: CMTime.init(value: 1, timescale: 1), queue: .main, using: { time in
        if let duration = player.currentItem?.duration {
          let duration = CMTimeGetSeconds(duration), time = CMTimeGetSeconds(time)
          let progress = (time/duration)
          if progress > targetProgress {
              print(progress)
             //Update slider value
          }
        }
    })

or

extension AVPlayer {
    func addProgressObserver(action:@escaping ((Double) -> Void)) -> Any {
        return self.addPeriodicTimeObserver(forInterval: CMTime.init(value: 1, timescale: 1), queue: .main, using: { time in
            if let duration = self.currentItem?.duration {
                let duration = CMTimeGetSeconds(duration), time = CMTimeGetSeconds(time)
                let progress = (time/duration)
                action(progress)
            }
        })
    }
}

Use

let player = AVPlayer()
player.addProgressObserver { progress in
   //Update slider value
}
like image 124
SPatel Avatar answered Nov 01 '22 07:11

SPatel


Put a UILabel at each end. Update them using -[AVPlayer addPeriodicTimeObserverForInterval:queue:usingBlock:]. Compute the time remaining using -[AVPlayer currentTime] and -[AVPlayerItem duration].

like image 42
rob mayoff Avatar answered Nov 01 '22 09:11

rob mayoff