我正在尝试提取 Firebase 数据库 url 引用的音频文件。我创建的功能是下载 [URL]
,但 AVAudioPlayer 需要一个可以在本地播放的 URL
。总体目标是流式传输音频文件。我的问题是有什么方法可以将此 url 从数组导出到常规 url 字符串?这SO post是我能做的最接近我的问题但并没有真正帮助。下面是 JSON 路径的代码片段和屏幕截图。非常感谢任何帮助和指导!
func fetchAudio(asset: AVURLAsset){
let storageRef = Storage.storage().reference() //Referencing database
var node : Post? //References the Post model
let remoteAudioURL = FetchAudio.shared.storageRef.reference(forURL: (node?.audioUrl)!) //Referencing the remote audio file by way of it's respective Post
let localURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) //Instantiate the local destination for the downloaded audio file
remoteAudioURL.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
if let error = error {
print (error.localizedDescription)
} else {
if let d = data {
do {
try d.write(to: localURL) //Error: Cannot convert value of type '[URL]' to expected argument type 'URL'
self.player = AVAudioPlayer(contentsOf: localURL) //Error: Cannot convert value of type '[URL]' to expected argument type 'URL'
self.player?.play()
} catch {
print(error)
}
}
}
}
}
最佳答案
通过使用 FileManager.default.urls(对于:.documentDirectory,在:.userDomainMask)
您获得的所有 URL 不是您播放特定音频文件或保存它所需的。
因此,为了实现您可能需要要求 FileManager 生成您的文件所在位置的 url,请执行以下操作:
let localURL = try! FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
.appendingPathComponent("yourFileName.mp3")
关于swift - 将 [URL] 提取到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51910676/