如何在AVPlayer中获取HLS流的视频大小?

Dix*_*ine 18 http-live-streaming ios avplayer swift

我正在尝试在播放hls流时获得视频分辨率.我有典型的玩家初始化:

let urlAsset = AVURLAsset(URL: currentVideoUrl)
 self.player=AVPlayer(playerItem: AVPlayerItem(asset:urlAsset))
 .......
Run Code Online (Sandbox Code Playgroud)

我使用KVO,当我获得AVPlayerItem的.ReadyToPlay状态时,我尝试获取视频大小:

    func resolutionSizeForVideo() {

    guard let videoTrack = self.player.currentItem?.asset.tracksWithMediaType(AVMediaTypeVideo).first else
    { return
    }

    let size = CGSizeApplyAffineTransform(videoTrack.naturalSize, videoTrack.preferredTransform)
    let frameSize = CGSize(width: fabs(size.width), height: fabs(size.height))
    print ("video size: \(frameSize)")

}
Run Code Online (Sandbox Code Playgroud)

问题是tracksWithMediaType()总是返回空数组(但适用于非流文件,例如.mov).

如何在AVPlayer中播放HLS视频的大小(CGRect)?

tym*_*mac 11

您是否能够使用此方法至少记录视频信息?

func checkVideoRez(videoURL: NSURL) -> Bool {

let videoAssetSource = AVAsset.init(URL: videoURL)
let videoTrack = videoAssetSource.tracksWithMediaType(AVMediaTypeVideo)[0]
let size = videoTrack.naturalSize
let txf = videoTrack.preferredTransform

let realVidSize = CGSizeApplyAffineTransform(size, txf)

print(videoTrack)
print(txf)
print(size)
print(realVidSize)

...

}
Run Code Online (Sandbox Code Playgroud)

  • 在m3u8资产上为tracksWithMediaType(AVMediaTypeVideo)返回的值将是一个空数组,因此此代码将导致索引超出范围异常. (6认同)

Max*_*Max 10

使用HLS时,曲目将始终返回nil.如果你有一个UIView子类layerClass用AVPlayerLayer 覆盖它来播放视频你可以得到大小

playerView.layer.videoRect
Run Code Online (Sandbox Code Playgroud)

这只是视频而不是整个图层的大小.

或者,您可以使用KVO观察项目的presentationSize

player.addObserver(self, forKeyPath: "currentItem.presentationSize", options: [.Initial, .New], context: nil)
Run Code Online (Sandbox Code Playgroud)

  • 你可以随时使用player.currentItem.presentationSize getter,KVO只是为了方便起见.这将为您提供解决方案.周期性观察者中此命令的输出是`print(self?.mediaPlayer?.currentItem?.presentationSize)` - >`Optional((853.333312988281,480.0))` (2认同)
  • 发表评论说presentationSize 不是资产的原始大小,它实际上是播放器中视频的大小,但这似乎不正确。在我的应用程序中,即使在横向和纵向之间切换时,继续打印出来的尺寸也是 1280x720。删除了之前的评论,因为它在技术上不正确。 (2认同)