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

时间:2018-08-08 15:40:03

标签: ios xcode swift3 swift4 xcode9

我想从URL播放音频文件。我想在swift4和xcode 9中与avaudioplayer一起播放。因此,首先我在会话中下载该文件并播放该音频。但是有时avaudioplayer无法播放音频并显示错误。

代码:

func downloadFileFromURL(url: URL){

    var downloadTask:URLSessionDownloadTask
    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URL, response, error) -> Void in

        print("audio download response: \(String(describing: response))")

       SVProgressHUD.dismiss()

        if response != nil {

            if error != nil {

                print("audio file download error: \(String(describing: error))")

                return
            }

            DispatchQueue.main.async {

                self?.play(url: URL!)
            }

        } else {

            SVProgressHUD.dismiss()
            Config.shared.show_simple_alert(title: "Fail", message: "Sorry, Fail to play this music. Plase try another or later", context: self!)
        }
    })

    downloadTask.resume()

}

func play(url: URL) {

    print("playing \(url)")

    do {

        player = try AVAudioPlayer(contentsOf: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()

    } catch let error as NSError {

        print("playing error: \(error.localizedDescription)")

    } catch {

        print("AVAudioPlayer init failed")
    }
}


错误-播放错误:操作无法完成。 (OSStatus错误2003334207。)

2 个答案:

答案 0 :(得分:1)

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()
        }
    }
}

答案 1 :(得分:0)

最终的解决方案是我使用avaudio player从URL播放。但是,如果我只使用avplayer,它就可以正常工作。