3

I set up a video player using Player (using AVFoundation). I am trying to access and manipulate currentTime of the video however, the library is only providing duration of the video but not currentTime.

I am tweaking the demo project of Player.


Please check 'Updated' section below instead of here:

A friend told me I can achieve using that approach, but I couldn't really get how to adapt this approach in this case.

[NSTimer scheduledTimerWithInterval:1.0 target:self selector:@selector(refreshCurrentTimeTextField) userInfo:nil repeats:YES]

-(void)refreshCurrentTimeTextField {
    NSTimeInterval currentTime; 
    QTMovie *movie = [movieView movie];
    QTGetTimeInterval([movie currentTime], &currentTime);

    int hours = currentTime/3600;
    int minutes = (currentTime/60) % 60;
    int seconds = currentTime % 60;

    NSString *timeLabel;
    if(hours > 0) {
        timeLabel = [NSString stringWithFormat:@"%02i:%02i:%02i", hours, minutes, seconds];
    } else {
        timeLabel = [NSString stringWithFormat:@"%02i:%02i", minutes, seconds];
    }
    [yourTextField setStringValue:timeLabel];
}

If any of you guys used or stumbled on this library, is there any way of getting currentTime? Is there any alternative way of accessing/manipulating currentTime of the video?


Update:

Someone apparently gave the code for the importing & connecting UISlider for Objective-C for equivalent library PBJVideoPlayer in here. But I couldn't adapt the same approach on Swift for Player.

Snippet from link:

diff --git a/Pods/PBJVideoPlayer/Source/PBJVideoPlayerController.m b/Pods/PBJVideoPlayer/Source/PBJVideoPlayerController.m
index be6a7d1..51a420e 100644
--- a/Pods/PBJVideoPlayer/Source/PBJVideoPlayerController.m
+++ b/Pods/PBJVideoPlayer/Source/PBJVideoPlayerController.m
@@ -81,6 +81,8 @@ static NSString * const PBJVideoPlayerControllerReadyForDisplay = @"readyForDisp
     float _volume;
 }

+@property (nonatomic, strong) UISlider *slider;
+
 @end

 @implementation PBJVideoPlayerController
@@ -93,6 +95,16 @@ static NSString * const PBJVideoPlayerControllerReadyForDisplay = @"readyForDisp

 #pragma mark - getters/setters

+- (UISlider *)slider {
+    if (_slider == nil) {
+        _slider = [[UISlider alloc] initWithFrame:CGRectZero];
+        _slider.minimumValue = 0.0;
+        _slider.maximumValue = 0.0;
+        _slider.continuous = YES;
+    }
+    return _slider;
+}
+
 - (void)setVideoFillMode:(NSString *)videoFillMode
 {
    if (_videoFillMode != videoFillMode) {
@@ -311,6 +323,59 @@ static NSString * const PBJVideoPlayerControllerReadyForDisplay = @"readyForDisp
     NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];        
     [nc addObserver:self selector:@selector(_applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
     [nc addObserver:self selector:@selector(_applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
+
+    self.slider.hidden = YES;
+    [self.slider addTarget:self action:@selector(moveScrubber:) forControlEvents:UIControlEventValueChanged];
+    [self.view addSubview:self.slider];
+
+    __weak typeof(self) weak = self;
+    CMTime intervalSeconds = CMTimeMakeWithSeconds(0.25f, NSEC_PER_SEC);
+    [_player addPeriodicTimeObserverForInterval:intervalSeconds
+                                          queue:dispatch_get_main_queue()
+                                     usingBlock:^(CMTime time) {
+                                         [weak syncScrubber];
+                                     }];
+}
+
+- (void)syncScrubber
+{
+    CMTime duration = _player.currentItem.duration;
+    if (CMTIME_IS_INVALID(duration)) {
+        self.slider.maximumValue = 0.0;
+    } else {
+        Float64 seconds = CMTimeGetSeconds(duration);
+        if (isfinite(seconds)) {
+            self.slider.maximumValue = seconds;
+            Float64  current = CMTimeGetSeconds([_player currentTime]);
+            self.slider.value = current;
+        }
+    }
+}
+
+- (void)moveScrubber:(UISlider *)slider
+{
+    CMTime duration = _player.currentItem.duration;
+    if (CMTIME_IS_INVALID(duration)) {
+        self.slider.maximumValue = 0.0;
+    } else {
+        Float64 seconds = CMTimeGetSeconds(duration);
+        if (isfinite(seconds)) {
+            self.slider.maximumValue = seconds;
+            [_player seekToTime:CMTimeMakeWithSeconds(slider.value, NSEC_PER_SEC)];
+        }
+    }
+}
+
+- (void)viewDidAppear:(BOOL)animated
+{
+    [super viewDidAppear:animated];
+
+    CGRect sliderRect = self.view.frame;
+    sliderRect.origin.y = sliderRect.size.height - 40;
+    sliderRect.size.height = 40;
+    sliderRect.origin.x = self.view.frame.size.width/4.0;
+    sliderRect.size.width =  self.view.frame.size.width/2.0;
+    self.slider.frame = sliderRect;
 }

 - (void)viewDidDisappear:(BOOL)animated
@@ -402,11 +467,13 @@ typedef void (^PBJVideoPlayerBlock)();
             case PBJVideoPlayerPlaybackStateStopped:
             {
                 [self playFromBeginning];
+                self.slider.hidden = YES;
                 break;
             }
             case PBJVideoPlayerPlaybackStatePaused:
             {
                 [self playFromCurrentTime];
+                self.slider.hidden = YES;
                 break;
             }
             case PBJVideoPlayerPlaybackStatePlaying:
@@ -414,6 +481,7 @@ typedef void (^PBJVideoPlayerBlock)();
             default:
             {
                 [self pause];
+                self.slider.hidden = NO;
                 break;
             }
         }
@@ -511,6 +579,14 @@ typedef void (^PBJVideoPlayerBlock)();
                 _videoView.playerLayer.backgroundColor = [[UIColor blackColor] CGColor];
                 [_videoView.playerLayer setPlayer:_player];
                 _videoView.playerLayer.hidden = NO;
+
+                CMTime duration = _playerItem.duration;
+                if (CMTIME_IS_INVALID(duration)) {
+                    self.slider.maximumValue = 0.0;
+                } else {
+                    Float64 seconds = CMTimeGetSeconds(duration);
+                    self.slider.maximumValue = seconds;
+                }
                 break;
             }
             case AVPlayerStatusFailed:
senty
  • 12,385
  • 28
  • 130
  • 260

1 Answers1

8

I just run you GitHub project and i fixed it by following code:

In your Player.swift Class.

 player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 100), queue: dispatch_get_main_queue()) {
            [unowned self] time in
            let timeString = String(format: "%02.2f", CMTimeGetSeconds(time))

            print("time is \(timeString)")
            self.delegate?.playerPlaybackstimer(timeString)

            }

That Above method added in public convenience init() { funtion so that will be look like:

 public convenience init() {
        self.init(nibName: nil, bundle: nil)
        self.player = AVPlayer()




        self.player.actionAtItemEnd = .Pause
        self.player.addObserver(self, forKeyPath: PlayerRateKey, options: ([NSKeyValueObservingOptions.New, NSKeyValueObservingOptions.Old]) , context: &PlayerObserverContext)

        self.playbackLoops = false
        self.playbackFreezesAtEnd = false
        self.playbackState = .Stopped
        self.bufferingState = .Unknown


        player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 100), queue: dispatch_get_main_queue()) {
            [unowned self] time in
            let timeString = String(format: "%02.2f", CMTimeGetSeconds(time))

            print("time is \(timeString)")
            self.delegate?.playerPlaybackstimer(timeString)

            }

    }

After that i make a Delegate method in public protocol PlayerDelegate: classthat will be look like:

public protocol PlayerDelegate: class {
    func playerReady(player: Player)
    func playerPlaybackStateDidChange(player: Player)
    func playerBufferingStateDidChange(player: Player)

    func playerPlaybackWillStartFromBeginning(player: Player)
    func playerPlaybackDidEnd(player: Player)

     func playerPlaybackstimer(NSString: String)
}

Now go in your ViewController.swift class and add the following function:

func playerPlaybackstimer(NSString: String) {

        print("currunt time \(NSString)")
    }

Now run your project and enjoy.

Nitin Gohel
  • 49,482
  • 17
  • 105
  • 144