通过firebase的音频流
问题描述:
我已经直接在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
。 ,我只想流式传输音频。我能为此获得适当的解决方案吗?
答
这不是流式传输的答案。
这是下载文件,将其存储在本地并在文件完成下载后播放音频的答案。
使用路径字符串文件扩展得到一个火力地堡存储参考。使用我们用于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)
}
}
这是最小的代码。按你认为合适的方式实施错误处理。