获取视频的当前时间(播放器-Swift) [英] Getting Current Time of a Video (Player - Swift)

查看:206
本文介绍了获取视频的当前时间(播放器-Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用播放器(使用AVFoundation)设置了视频播放器.我正在尝试访问和操作视频的currentTime,但是该库仅提供视频的时长,而不提供currentTime.

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.

我正在调整播放器的演示项目.

请检查下面的已更新"部分,而不是此处:

一个朋友告诉我,我可以使用这种方法来实现,但是在这种情况下,我真的不知道如何适应这种方法.

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];
}

如果你们中有人使用或迷失了这个库,有什么方法可以获取currentTime吗?是否有其他方法可以访问/操纵视频的currentTime?

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?

更新:

显然有人给了导入&a​​mp;的代码.在相同的库此处的PBJVideoPlayer 中连接UISlider for Objective-C.但是我无法在Swift for Player中采用相同的方法.

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.

链接摘录:

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:

推荐答案

我只是运行了GitHub项目,并通过以下代码对其进行了修复:

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

在您的 Player.swift 课程中.

 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)

            }

public convenience init() {函数中添加了Above方法,其外观如下:

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)

            }

    }

之后,我在public protocol PlayerDelegate: class中创建一个Delegate方法,如下所示:

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)
}

现在进入您的ViewController.swift类并添加以下功能:

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.

这篇关于获取视频的当前时间(播放器-Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆