Why does Swift's AVPlayer loads the playerItem for twice on one play?

六眼飞鱼酱① 提交于 2019-12-23 18:24:21

问题


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

回答1:


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)

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.



来源:https://stackoverflow.com/questions/37244956/why-does-swifts-avplayer-loads-the-playeritem-for-twice-on-one-play

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!