2016-11-03 4 views
0

私はAlamofireでmp3ファイルをダウンロードしようとしています。私はファイルを取得して、それをデータファイル(mp3拡張子ではない)としてデバイスストレージ内の目的のパスに保存しています。そして、私はAVAudioPlayer(これもAVPlayerで試してみた)で再生しようとしていますが、成功しません。そのデータファイルをアンラップしている間、それはnilを見つけました。このファイルは、サイズが7MBを超えているので有効で、拡張子が.mp3のコンピュータで再生できます。AVAudioPlayerがURLファイルからnilを見つけました

私の質問は、ファイルがパスで有効な場合、なぜnilが見つかりましたか?

func playSong() { 

    guard let songs = currentPlaylist?.getSongs() else { return } 

    let song = songs[0] 

    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! 

    let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(song.getID())") 
    print(destinationUrl) 

    if FileManager.default.fileExists(atPath: destinationUrl.path) { 
     print("The song already exists") 
     do { 
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) 
      try AVAudioSession.sharedInstance().setActive(true) 

      let soundData = try Data(contentsOf: destinationUrl) 

      player! = try AVAudioPlayer(data: soundData) 

      player!.play() 
     } catch let error as NSError { 
      print("AVAudioPlayer Error: \(error.localizedDescription)") 
     } 

    } else { 
     print("Song was not found. Starting download proccess") 
     APIService.sharedService.downloadSong(song: song) { (success) in 
      if !success { 
       print("Failed to download the song") 
      } else { 
       print("Downloaded the song") 
      } 
     } 
    } 
} 

私は、どのように私は正しい方法で、そのファイルにアクセスする必要があるなど、URL、PlayerItemとしてAVPlayerを試してみましたか?

答えて

0

解決策が見つかりました。それはデータの不具合ではなく、無事は選手だった。 それは

player = try AVAudioPlayer(data: soundData) 

なく

player! = try AVAudioPlayer(data: soundData) 
として宣言する必要があります
関連する問題