AVAudioPlayer not playing m4a or mp3 filetype from a website

后端 未结 1 879
执念已碎
执念已碎 2021-01-28 21:20

I am trying to locate a URL which is only pure .m4a sound with my application. I have the URL to the audio and theoretically download it. Then, with the downloaded fileURL to th

相关标签:
1条回答
  • 2021-01-28 22:01

    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
    
                    try FileManager.default.removeItem(atPath: desURL.path)
                    try FileManager.default.copyItem(at: URLData!, to: desURL)
    
                } 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.

    0 讨论(0)
提交回复
热议问题