AVAudioPlayer 不从网站播放 m4a 或 mp3 文件类型

AVAudioPlayer not playing m4a or mp3 filetype from a website

我正在尝试找到一个 URL,它只是我的应用程序的纯 .m4a 声音。我有音频的 URL 并且理论上可以下载它。然后,将下载的文件URL添加到声音中,我尝试用AVAudioPlayer播放它,但它没有播放任何声音。这是我的代码:

在 URL 检索函数中,我调用:(urls 定义为 URL(string: url),url 是检索 URL 字符串)

downloadSound(url: urls!)

这是我的 downloadSound() 函数:

func downloadSound(url:URL){

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

最后是 playSound 函数:

func playSound(url:URL) {
    print("The url is \(url)")
    let player = try! AVAudioPlayer(contentsOf: url)
    player.play()

一切都被称为 print("The url is \(url)") returns 我文件的路径(但是我实际上无法跟踪文件)。

模拟器上声音的大致路径如下:

file:///Users/[...]/Library/Developer/CoreSimulator/Devices/116C311A-C7F3-44EC-9762-2FAA0F9FE966/data/Containers/Data/Application/60BFCDE7-AC02-4196-8D1A-24EC646C4622/tmp/CFNetworkDownload_7VDpsV.tmp

而 运行 它在 phone returns:

file:///private/var/mobile/Containers/Data/Application/C75C1F1D-77E9-4795-9A38-3F0756D30547/tmp/CFNetworkDownload_T1XlPb.tmp

提前谢谢你。

我遇到了同样的问题,我选择了一个替代解决方案,正如应用文档所说:

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.

思路就是从tmp目录复制到document目录,然后从document目录播放。

创建成员变量:

var player = AVAudioPlayer()

现在实现您的 downloadSound 方法如下:

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

这只是一个示例解决方案。