Swift:从 avaudioplayer 中的 url 下载后无法播放音频文件

Sar*_*han 1 xcode ios swift3 swift4 xcode9

我想从 url 播放音频文件。我想在 swift4 和 xcode 9 中使用 avaudioplayer 来播放这个。所以,首先我在会话中下载这个并播放该音频。但有时 avaudioplayer 无法播放音频并显示错误。

\n\n

代码:

\n\n
func downloadFileFromURL(url: URL){\n\n    var downloadTask:URLSessionDownloadTask\n    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URL, response, error) -> Void in\n\n        print("audio download response: \\(String(describing: response))")\n\n       SVProgressHUD.dismiss()\n\n        if response != nil {\n\n            if error != nil {\n\n                print("audio file download error: \\(String(describing: error))")\n\n                return\n            }\n\n            DispatchQueue.main.async {\n\n                self?.play(url: URL!)\n            }\n\n        } else {\n\n            SVProgressHUD.dismiss()\n            Config.shared.show_simple_alert(title: "Fail", message: "Sorry, Fail to play this music. Plase try another or later", context: self!)\n        }\n    })\n\n    downloadTask.resume()\n\n}\n\nfunc play(url: URL) {\n\n    print("playing \\(url)")\n\n    do {\n\n        player = try AVAudioPlayer(contentsOf: url)\n        player.prepareToPlay()\n        player.volume = 1.0\n        player.play()\n\n    } catch let error as NSError {\n\n        print("playing error: \\(error.localizedDescription)")\n\n    } catch {\n\n        print("AVAudioPlayer init failed")\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n


\n错误 - 播放错误:操作无法完成\xe2\x80\x99。(操作系统状态错误 2003334207。)

\n

Ish*_*ngu 5

func downloadFileFromURL(url: String)  {

    if let audioUrl = URL(string: url) {

        // 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")
            self.play(url: destinationUrl)
        } 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)

                    self.play(url: destinationUrl)
                    print("File moved to documents folder")
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }).resume()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)