Как получить Duration от AVPlayer (не AVAudioPlayer)? - PullRequest
37 голосов
/ 20 октября 2010

Я хотел бы сделать UISlider (скруббер) для моего AVPlayer.Но так как это не AVAudioPlayer, он не имеет встроенной длительности.Любое предложение о том, как создать слайдер для быстрой перемотки вперед, назад и прогресса воспроизведения?

Я прочитал документ на AVPlayer, он имеет встроенный seekToTime или seekToTime: толерантностьBefore: толерантностьAfter :.Я не очень понимаю это.Будет ли это ответом для моего слайдера?AVPlayer также имеет addPeriodicTimeObserverForInterval: queue: usingBlock: это для получения продолжительности моего трека?Может кто-нибудь дать мне пример того, как реализовать этот код?Я не фанат документации Apple.Кажется, это очень трудно понять.

Ответы [ 6 ]

123 голосов
/ 22 октября 2010
self.player.currentItem.asset.duration

Понял!

35 голосов
/ 26 мая 2011

заголовки

#import <AVFoundation/AVPlayer.h>
#import <AVFoundation/AVPlayerItem.h>
#import <AVFoundation/AVAsset.h>

код

CMTime duration = self.player.currentItem.asset.duration;
float seconds = CMTimeGetSeconds(duration);
NSLog(@"duration: %.2f", seconds);

рамки

AVFoundation
CoreMedia
12 голосов
/ 27 июня 2016

Для Swift, чтобы получить длительность в секундах

if let duration = player.currentItem?.asset.duration {
    let seconds = CMTimeGetSeconds(duration)
    print("Seconds :: \(seconds)")
}
11 голосов
/ 07 мая 2013

Начиная с iOS 4.3, вы можете использовать немного короче:

self.player.currentItem.duration;
4 голосов
/ 05 сентября 2014

Отмечено с StitchedStreamPlayer

Вы должны использовать player.currentItem.duration

- (CMTime)playerItemDuration
{
    AVPlayerItem *thePlayerItem = [player currentItem];
    if (thePlayerItem.status == AVPlayerItemStatusReadyToPlay)
    {        
        /* 
         NOTE:
         Because of the dynamic nature of HTTP Live Streaming Media, the best practice 
         for obtaining the duration of an AVPlayerItem object has changed in iOS 4.3. 
         Prior to iOS 4.3, you would obtain the duration of a player item by fetching 
         the value of the duration property of its associated AVAsset object. However, 
         note that for HTTP Live Streaming Media the duration of a player item during 
         any particular playback session may differ from the duration of its asset. For 
         this reason a new key-value observable duration property has been defined on 
         AVPlayerItem.

         See the AV Foundation Release Notes for iOS 4.3 for more information.
         */     

        return([playerItem duration]);
    }

    return(kCMTimeInvalid);
}
3 голосов
/ 10 декабря 2015

В этом примере avPlayer является экземпляром AVPlayer.

Я построил элемент управления видео, который использует следующее:

для позиционирования ползунка используйте что-то вроде этого, чтобы получить процент воспроизведения в фильме, вам нужно будет запускать эту функцию несколько раз. Поэтому я бы запустил функцию как:

float scrubberBarLocation = (scrubberBgImageView.frame.size.width / 100.0f) * [self moviePercentage];


- (float)moviePercentage {

    CMTime t1 = [avPlayer currentTime];
    CMTime t2 = avPlayer.currentItem.asset.duration;

    float myCurrentTime = CMTimeGetSeconds(t1);
    float myDuration = CMTimeGetSeconds(t2);

    float percent = (myCurrentTime / myDuration)*100.0f;
    return percent;

}

Затем, чтобы обновить видео, я бы сделал что-то вроде:

- (void)updateVideoPercent:(float)thisPercent {

    CMTime t2 = avPlayer.currentItem.asset.duration;
    float myDuration = CMTimeGetSeconds(t2);

    float result = myDuration * thisPercent /100.0f;

    //NSLog(@"this result = %f",result); // debug

    CMTime seekTime = CMTimeMake(result, 1);

    [avPlayer seekToTime:seekTime];

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...