AVPlayer太长,延迟到readyToPlay并在swift

时间:2017-02-08 10:25:02

标签: ios swift avplayer avplayeritem

我尝试使用快速语言缓冲并立即播放remote url音频。

但问题是readyToPlay案例和游戏的时间很长。

例如声音网址大约需要12到15秒才能运行。

这是我的代码:

var asset: AVAsset!
var player: AVPlayer!
var playerItem: AVPlayerItem!

private var playerItemContext = 0

let requiredAssetKeys = [ "playable","hasProtectedContent"]
let url = URL(string: "http://sound_link.mp3")!
asset = AVAsset(url: url)

playerItem = AVPlayerItem(asset: asset,
                              automaticallyLoadedAssetKeys: requiredAssetKeys)
playerItem.addObserver(self,
                       forKeyPath: #keyPath(AVPlayerItem.status),
                       options: [.old, .new],
                       context: &playerItemContext)

player = AVPlayer(playerItem: playerItem)

根据此(ExploringAVFoundation) documentation've done that

并且对于玩家已准备好玩牌的手柄我使用observeValue func

override func observeValue(forKeyPath keyPath: String?,of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

   guard context == &playerItemContext else {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        return
    }

    if keyPath == #keyPath(AVPlayerItem.status) {
        let status: AVPlayerItemStatus
        if let statusNumber = change?[.newKey] as? NSNumber {
            status = AVPlayerItemStatus(rawValue: statusNumber.intValue)!
        } else {
            status = .unknown
        }
        // Switch over status value
        switch status {
        case .readyToPlay:
            print("readyToPlay \(status.rawValue)")
            player.play() // here play remote sound
        case .failed:
            print("readyToPlay \(status.rawValue)")
        case .unknown:
            print("failed \(status.rawValue)")
        }

    }
}

这是返回日志:

2017-02-08 13:44:00.626036 [15144:3747850] [aqme] 255: AQDefaultDevice (1): skipping input stream 0 0 0x0
readyToPlay 1
2017-02-08 13:44:02.631182 [15144:3747850] [aqme] 255: AQDefaultDevice (173): skipping input stream 0 0 0x0

在上面的日志中,需要4秒才能显示readyToPlay 1然后需要10秒才能播放声音

服务器速度很好,我尝试在Android播放服务器声音,缓冲和播放声音的最长时间约为3秒(在Android应用程序中),但在IOS缓冲完全播放声音,大约需要15秒!

感谢您的关注

2 个答案:

答案 0 :(得分:14)

尝试使用它:

player.automaticallyWaitsToMinimizeStalling = false

答案 1 :(得分:5)

尝试用URL实例化你的@Override public int getViewTypeCount() { return 1; } @Override public int getItemViewType(int position) { return position; } ,然后在全局线程中获取其他资产,我认为问题发生是因为avPlayerItem试图在主UI线程中获取资产 当我尝试从avPlayer读取字幕选项时,我遇到了同样的问题 在我的播放器中加载电影需要花费5-6秒

这就是我解决问题的方法(在Swift 2中),我希望它有所帮助:

avAssets