我正在使用AVPlayer在我的應用&中正常播放。下載文件導致問題在ios中流式傳輸
但是,當我嘗試使用Alamofire.downlaod method
下載某個文件時,流將停止工作。
AVPlayer
的rate
屬性爲自動爲零。
我覺得線程可能存在一些問題,但我沒有得到它。
我的代碼如下
override func viewDidLoad() {
play_Live_Stream()
}
override func viewWillAppear() {
Download_favourite_files()
}
func Download_favourite_files() {
for int i in arr_favourites{
Alamofire.download(urlString, to: destination).response { response in
print(response)
}
}
}
func play_Live_Stream(){
myplayerItem = AVPlayerItem(url: url as! URL)
myPlayer = AVPlayer(playerItem: myplayerItem)
myPlayer.volume = volume_slider.value
PlayerObserving = true
NotificationCenter.default.addObserver(self, selector: #selector(playInstalled(noti:)), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: myPlayer.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(playfailed(noti:)), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: myPlayer.currentItem)
myPlayer.currentItem?.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)
myPlayer.currentItem?.addObserver(self, forKeyPath: "timedMetadata", options: [.new,.old,.initial], context: nil)
myPlayer.currentItem?.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if ((object! as AnyObject).isEqual(myPlayer.currentItem) && keyPath=="status"){
if myPlayer.status == AVPlayerStatus.readyToPlay{
print("ReadyToPlay")
myPlayer.play()
}
}
TRY 2(默認NSURLSession)
func load_downloads(){
for track in arr_tracks{
let urlString = BASE_URL + "/track/download/" + "\(track.id)"
print("downloaded url",urlString)
let url = NSURL(string: urlString)
let downloadTask = backgroundSession.downloadTask(with: url as! URL)
downloadTask.resume()
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let destinationURLForFile = documentsURL.appendingPathComponent((downloadTask.originalRequest?.url?.lastPathComponent)! + "_" + (downloadTask.response?.suggestedFilename)!)
let fileManager = FileManager()
if fileManager.fileExists(atPath: destinationURLForFile.path){
}
else{
do {
try fileManager.moveItem(at: location as URL, to: destinationURLForFile as URL)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
但它並沒有給我爲什麼流停止任何信息。 我也觀察失速&失敗的信息,如果有的話。
你能展示'play_Live_Stream'的實現嗎? –
@RhythmicFistman,我添加了播放流的代碼。 – user2526811
一次下載多少個文件?不要一次啓動所有下載,您可以嘗試一次下載一個嗎?也許你正在飽和你的連接。你是否觀察到'playbackLikelyToKeepUp'的任何改變? –