swift URLSession响应数据保存和播放音频文件

时间:2016-12-24 09:16:26

标签: swift audio request response

我有一些问题需要从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!)
    }

1 个答案:

答案 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")
    }
}