如何首先从URL下载音频文件,然后播放所有

时间:2018-05-24 10:06:13

标签: swift audio

我在服务器上有多个音频文件。 我想首先下载所有音频文件,然后当全部下载时,我需要一个接一个地播放它们。 实现这一目标的最佳方法是什么?

谢谢!

if let audioUrl = URL(string: "http://freetone.org/ring/stan/iPhone_5-Alarm.mp3") {

    // then lets create your document folder url
    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    // lets create your destination file url
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    print(destinationUrl)

    // to check if it exists before downloading it
    if FileManager.default.fileExists(atPath: destinationUrl.path) {
        print("The file already exists at path")

        // if the file doesn't exist
    } else {

        // you can use NSURLSession.sharedSession to download the data asynchronously
        URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
            guard let location = location, error == nil else { return }
            do {
                // after downloading your file you need to move it to your destination url
                try FileManager.default.moveItem(at: location, to: destinationUrl)
                print("File moved to documents folder")
            } catch let error as NSError {
                print(error.localizedDescription)
            }
        }).resume()
    }
}

0 个答案:

没有答案