gpt4 book ai didi

ios - swift : Fail to play audio file after downloading from a url in avaudioplayer

转载 作者:行者123 更新时间:2023-11-29 11:33:01 29 4
gpt4 key购买 nike

我想从 url 播放音频文件。我想在 swift4 和 xcode 9 中用 avaudioplayer 播放这个。所以,首先我在 session 中下载这个并播放那个音频。但有时 avaudioplayer 无法播放音频并显示错误。

代码:

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


错误 - 播放错误:操作无法完成。 (操作系统状态错误 2003334207。)

最佳答案

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

关于ios - swift : Fail to play audio file after downloading from a url in avaudioplayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51750657/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com