iOS 7中的iOS 7 AVPlayer AVPlayerItem持续时间不正确

问题描述 投票:28回答:4

我的应用程序中有以下代码:

NSURL *url = [NSURL fileURLWithPath: [self.DocDir stringByAppendingPathComponent: self.FileName] isDirectory: NO];
self.avPlayer = [AVPlayer playerWithURL: url];

Float64 duration = CMTimeGetSeconds(self.avPlayer.currentItem.duration);

这适用于iOS 6,但由于某种原因,iOS 7会返回NaN。检查self.avPlayer.currentItem.duration时,CMTime对象的值为0,标志为17。

有趣的是,玩家工作正常,只是持续时间是错误的。

还有其他人遇到过同样的问题吗?我正在导入以下内容:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVAsset.h>
ios ios7 avfoundation avplayer avasset
4个回答
49
投票

在使用不同的初始化对象的方法后,我找到了一个有效的解决方案:

AVURLAsset *asset = [AVURLAsset assetWithURL: url];
Float64 duration = CMTimeGetSeconds(asset.duration);
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset]; 
self.avPlayer = [[AVPlayer alloc] initWithPlayerItem: item];

看起来持续时间值并不总是立即从AVPlayerItem可用,但它似乎立即与AVAsset一起正常工作。


27
投票

在iOS 7中,对于已创建的AVPlayerItem,您还可以从基础资产获取持续时间:

CMTimeGetSeconds([[[[self player] currentItem] asset] duration]);

而不是直接从AVPlayerItem获取它,它给你一个NaN:

CMTimeGetSeconds([[[self player] currentItem] duration]);

5
投票

the manual中所述,建议的方法是观察玩家项目状态:

[self.avPlayer.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial context:nil];

然后,在observeValueForKeyPath:ofObject:change:context内:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    // TODO: use either keyPath or context to differentiate between value changes
    if (self.avPlayer.currentItem.status == AVPlayerStatusReadyToPlay) {
        Float64 duration = CMTimeGetSeconds(self.avPlayer.currentItem.duration);
        // ...
    }
}

此外,请确保在更改播放器项目时删除观察者:

if (self.avPlayer.currentItem) {
    [self.avPlayer.currentItem removeObserver:self forKeyPath:@"status"];
}

顺便说一句,你也可以直接观察duration的财产;然而,这是我个人的经验,结果并不像他们应该的那样可靠;-)


0
投票

Swift版本

你可以使用AVAsset获得持续时间,这是AVPlayerItem属性:

func getVideoDuration(from player: AVPlayer) -> Double? {
    guard let duration = player.currentItem?.asset.duration else { return nil }
    let durationSeconds = CMTimeGetSeconds(duration)
    return durationSeconds
}

或者从头开始创建AVAsset

func getVideoDuration(for videoUrl: URL) -> Double {
    let asset = AVAsset(url: videoUrl)
    let duration = asset.duration
    let durationSeconds = CMTimeGetSeconds(duration)
    return durationSeconds
}
© www.soinside.com 2019 - 2024. All rights reserved.