为什么Swift的AVPlayer会在一次播放中将playerItem加载两次? [英] Why does Swift's AVPlayer loads the playerItem for twice on one play?

查看:74
本文介绍了为什么Swift的AVPlayer会在一次播放中将playerItem加载两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AVFoundation的AVPlayer来流式传输外部mp3文件.我在后端有一个计数器,可以计算文件加载的次数.此服务的唯一客户端只有我一个,每当我触发播放AVPlayer时,计数器就会增加2,这意味着AVPlayer发出两次请求.是否有这个原因,或者如何防止这种情况发生?这是我的代码:

I'm using AVFoundation's AVPlayer for streaming external mp3 files. I have a counter on the back-end that counts how many times a file loaded. The only client for this service is only me and whenever I trigger to play the AVPlayer, the counter increases two which means AVPlayer makes the request twice. Is there a reason for this, or how can I prevent that from happening? Here is my code:

@IBAction func listen(sender: UIButton) {
    let urlstring = "http://api.server.com/endpoint-to-mp3"
    let url = NSURL(string: urlstring)

    let playerItem = AVPlayerItem(URL: url!)

    let player = AVPlayer(playerItem: playerItem)

    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = CGRectMake(0, 0, 300, 50)
    self.view.layer.addSublayer(playerLayer)

    player.volume = 1.0
    player.play()
}

每当您使用AVPlayerItem初始化播放器时,

推荐答案

AVPlayer就会向URL发出网络请求.该调用仅获取文件信息和文件大小. (此时,我有时可以观察到2个请求,这可能会使您的请求数增加到3个)

AVPlayer is making a network request to the URL whenever you initialize the player with AVPlayerItem. This call only fetches the file information and file size. (At this point I am able to observe 2 requests sometime, which could increase your count to 3)

稍后,将播放器附加到任何视图时,发生另一个调用以获取完整文件. (您可以使用查尔斯观察网络流量,仅供参考)

Later when you are attaching the player to any view, another call is happening to fetch the complete file. (You can use Charles to observe your network traffic, fyi)

当您使用init(url:)播放器init时,这种行为是相同的,因此我目前看不到任何可以阻止这种情况发生的方法.

This behaviour is same when you init the player with init(url:) So I don't see any way that could prevent this from happening at the moment.

这篇关于为什么Swift的AVPlayer会在一次播放中将playerItem加载两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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