Sarwar Jahan
Sarwar Jahan

Reputation: 63

Swift: Fail to play audio file after downloading from a url in avaudioplayer

I want to play audio file from a url. I wanna play this with avaudioplayer in swift4 and xcode 9. So, first I download this in session and play that audio. But some times avaudioplayer fail to play audio and shows an error.

Code:

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


The Error - playing error: The operation couldn’t be completed. (OSStatus error 2003334207.)

Upvotes: 1

Views: 1981

Answers (2)

Sarwar Jahan
Sarwar Jahan

Reputation: 63

The final solution is that I was using avaudio player to play from the url. But if I use just avplayer then it works fine.

Upvotes: 1

Ishwar Hingu
Ishwar Hingu

Reputation: 560

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

Upvotes: 5

Related Questions