Soumya Das
Soumya Das

Reputation: 1665

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.

Upvotes: 5

Views: 9732

Answers (3)

SPatel
SPatel

Reputation: 4946

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
}

Upvotes: 12

Chu Chau
Chu Chau

Reputation: 70

[slider setMaximumValue:[AVPlayerItem duration]];
//use NSTimer, run repeat function
-(void)updateValueSlide{
      [slider setValue:[AVPlayerItem duration]];
 }

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385500

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

Upvotes: 6

Related Questions