![](/img/trans.png)
[英]How to only play videoPreviewLayer when AVPlayer item is “.readyToPlay”
[英]AVPlayer too long and with delay to readyToPlay and play server music in swift
我嘗試緩沖並立即使用 swift 語言播放remote url
音頻。
但問題是很長的時間來readyToPlay
播放案例和播放。
例如,聲音 url 大約需要 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)文檔已經做到了
並且為了處理那個玩家准備好播放我使用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 秒!
感謝您的關注
嘗試使用這個:
player.automaticallyWaitsToMinimizeStalling = false
嘗試使用 URL 實例化您的avPlayerItem
,然后在全局線程中獲取其他資產,我認為問題的發生是因為avPlayer
試圖在主 UI 線程中獲取資產我在嘗試從avAssets
讀取字幕選項時遇到了同樣的問題,它花了 5 -6 秒后在我的播放器中加載電影。
這就是我解決問題的方法(在 Swift 2 中),希望對您有所幫助:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let avMediaSelectionGroup : AVMediaSelectionGroup? = self.container.player.currentItem?.asset.mediaSelectionGroupForMediaCharacteristic(AVMediaCharacteristicLegible)
dispatch_async(dispatch_get_main_queue(), {
if (avMediaSelectionGroup != nil && (avMediaSelectionGroup!.options.count != 0) && avMediaSelectionGroup?.options[0].valueForKey("title") != nil)
{
// show hide subtitle button
}
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.