AVAudioPlayer not playing m4a or mp3 filetype from a website

Deadly 提交于 2019-12-02 11:22:43

I had the same problem and I choosed an alternative solution as app doc said:

A file URL for the temporary file. Because the file is temporary, you must either open the file for reading or move it to a permanent location in your app’s sandbox container directory before returning from this delegate method.

The idea is just to copy from tmp directory to document directory and play from document directory.

Create a member variable:

var player = AVAudioPlayer()

Now implement your downloadSound method as below:

func downloadSound(url:URL){
    let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let desURL = docUrl.appendingPathComponent("tmpsong.m4a")
    var downloadTask:URLSessionDownloadTask
    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URLData, response, error) -> Void in
        do{
            let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
            if isFileFound == true{
                  print(desURL) //delete tmpsong.m4a & copy
            } else {
                try FileManager.default.copyItem(at: URLData!, to: desURL)
            }
            let sPlayer = try AVAudioPlayer(contentsOf: desURL!)
            self?.player = sPlayer
            self?.player.prepareToPlay()
            self?.player.play()

        }catch let err {
            print(err.localizedDescription)
        }

        })
    downloadTask.resume()
}

This is just a sample solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!