2016-04-14 136 views
0

我一直在從事一個小型項目,涉及從Web服務器下載視頻文件,將所述文件複製到文檔目錄,然後通過AVPlayer播放。AVPlayer&視頻文件目錄

將文件下載到文檔目錄不是問題。我可以下載文件並保存,沒有問題。但是,在將文件加載到AVPlayer中時,我在AVPlayerViewController的實例中播放它,視頻控制器彈出,但視頻無法加載。

我意識到,在模擬器中測試時,每次重建項目時文檔目錄都會發生更改。這就是爲什麼我在播放前檢查文件是否存在,儘管我知道該文件存在,但它仍然拒絕播放。

這裏是我的播放器代碼的樣子:

 let fileName = downloadURL.characters.split("/").map(String.init).last as String! 
     let fileNameHD = downloadURLHD.characters.split("/").map(String.init).last as String! 
     let downloadFilePath = getDocumentsDirectory() + "/" + "\(fileNameHD)" 

     let checkValidation = NSFileManager.defaultManager() 

     if checkValidation.fileExistsAtPath(downloadFilePath){ 
      print("video found") 
     } 

     let videoFile = NSURL(string:downloadFilePath) 
     let player = AVPlayer(URL: videoFile!) 
     let playerController = AVPlayerViewController() 
     playerController.player = player 
     playerController.view.frame = self.view.frame 
     player.play() 
     self.presentViewController(playerController, animated: true) { 
      playerController.player!.play() 
     } 

回答

0

嘗試AVPlayer而不是像AVPlayerViewController

let videoURL = NSURL(string: "your url string") 
let player = AVPlayer(URL: videoURL!) 
let playerLayer = AVPlayerLayer(player: player) 
playerLayer.frame = self.view.bounds 
self.view.layer.addSublayer(playerLayer) 
player.play() 

和進口AVKit,進口AVFoundation。

OR用的viewController這樣,

let player = AVPlayer(URL: url) 
let playerController = AVPlayerViewController() 

playerController.player = player 
self.addChildViewController(playerController) 
self.view.addSubview(playerController.view) 
playerController.view.frame = self.view.frame 

player.play()