我有一些问题需要从URLSession
请求的响应数据中保存和播放音频文件。如何从响应数据中播放音频文件?
let task = URLSession.shared.dataTask(with: request) {data, response, error in
if let error = error {
print("Error:", error)
}
if let response = response {
print("Voice Response:", response)
}
self.playMusic(data: data!)
}
答案 0 :(得分:1)
我自己解决了以下问题:
func playMusic(data: Data) {
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("voice.mp3")
do {
try data.write(to: fileURL, options: .atomic)
} catch {
print("Error")
print(error)
}
do{
audio = try AVAudioPlayer(contentsOf: fileURL)
audio.prepareToPlay()
audio.play()
}
catch {
print("Error")
}
}