2017-07-03 121 views
1

我已經直接在firebase存儲中上傳了一些歌曲,我只是想在AVAudioPlayer中播放歌曲。 下面是我試圖代碼:通過firebase的音頻流

var mainRef : FIRStorageReference{ 
     return FIRStorage.storage().reference(forURL: "gs://musicapp-d840c.appspot.com") 
     } 
    var audioStorageRef : FIRStorageReference{ 
     return mainRef.child("SongsPath") 
    } 

audioStorageRef.downloadURL { url, error in 
      if let error = error { 
       print(error.localizedDescription) 
      } else { 
       if let url = url{ 

        do { 
          self.audioPlayer = try AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: String(describing: url)) as URL) 
          self.audioPlayer.play() 
        } 
        catch { 

        } 
        let storyboard = UIStoryboard(name: "AudioPlayer", bundle: nil) 
        let audioVc = storyboard.instantiateViewController(withIdentifier: "AudioPlayerViewController") as! AudioPlayerViewController 
        audioVc.playThisSong = String(describing: url) 
        self.present(audioVc, animated: false, completion: nil) 

       } 
      } 
     } 

這裏從firebase歌曲的URL被傳遞,但它跳過self.audioPlayer.play。 ,我只想流式傳輸音頻。我能爲此獲得適當的解決方案嗎?

回答

0

這不是流式傳輸的答案。

這是下載文件,將其存儲在本地並在文件完成下載後播放音頻的答案。

使用路徑字符串文件擴展得到一個火力地堡存儲參考。使用我們用於Firebase存儲參考的相同路徑字符串獲取文件url以將其存儲在設備上。

使用write(toFile:URL)啓動下載任務。將下載任務存儲在變量中以添加觀察者。下載成功後播放音頻。

在夫特4:

var player: AVAudioPlayer? 

let pathString = "SongsPath.mp3" 
let storageReference = Storage.storage().reference().child(pathString) 
let fileUrls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 

guard let fileUrl = fileUrls.first?.appendingPathComponent(pathString) else { 
    return 
} 

let downloadTask = storageReference.write(toFile: fileUrl) 

downloadTask.observe(.success) { _ in 
    do { 
     self.player = try AVAudioPlayer(contentsOf: fileUrl) 
     self.player?.prepareToPlay() 
     self.player?.play() 
    } catch let error { 
     print(error.localizedDescription) 
    } 
} 

這是最小的代碼。按你認爲合適的方式實施錯誤處理。

Firebase example of downloading locally