我直接在firebase Storage中上传了一些歌曲,我只是想在AVAudioPlayer中播放歌曲。 下面是我正在尝试的代码:
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 存储引用。使用我们用于 Firebase 存储引用的相同路径字符串获取文件 url 以将其存储在设备上。
使用 write(toFile: URL) 启动下载任务。将下载任务存储在变量中以添加观察者。下载成功后,播放音频。
在 Swift 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)
}
}
这是最少的代码。实现您认为合适的错误处理。
关于ios - 通过 firebase 的音频流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44881398/