我正在尝试通过我的应用程序找到一个纯 .m4a 声音的 URL。我有音频的 URL,理论上可以下载它。然后,使用下载到声音的 fileURL,我尝试使用 AVAudioPlayer 播放它,但它不播放任何声音。这是我的代码:
在 URL 检索函数中,我调用:(定义为 URL(string: url)
的 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)")
返回文件的路径(但是我实际上无法跟踪文件)。
下面是声音在模拟器上的一般路径:
file:///Users/[...]/Library/Developer/CoreSimulator/Devices/116C311A-C7F3-44EC-9762-2FAA0F9FE966/data/Containers/Data/Application/60BFCDE7-AC02-4196 -8D1A-24EC646C4622/tmp/CFNetworkDownload_7VDpsV.tmp
而在手机上运行它会返回:
file:///private/var/mobile/Containers/Data/Application/C75C1F1D-77E9-4795-9A38-3F0756D30547/tmp/CFNetworkDownload_T1XlPb.tmp
提前谢谢你。
最佳答案
我遇到了同样的问题,我选择了一个替代解决方案,正如 app doc 所说:
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()
}
这只是一个示例解决方案。
关于ios - AVAudioPlayer 不从网站播放 m4a 或 mp3 文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391623/