0
我试图用Alamofire下载mp3文件并将其保存到所需的位置。然后,从那个位置,我试图播放该文件,但它给了我一个错误。OSStatus错误1685348671 AVAudioPlayer
这是下载功能
func downloadSong(song: Song, completion: @escaping(Bool) ->()) {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: Constants.authName, password: Constants.authKey) {
headers[authorizationHeader.key] = authorizationHeader.value
}
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("\(song.getID()).mp3")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(APIEndpoint.Song(id: song.getID(), token: self.authToken!).path(), method: .get, headers: headers, to: destination).response { (response) in
if response.error == nil, let filePath = response.destinationURL?.path {
print(filePath)
completion(true)
} else {
completion(false)
}
}
}
这是一个播放功能
func playSong() {
guard let songs = currentPlaylist?.getSongs() else { return }
let song = songs[0]
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent("\(song.getID()).mp3")
print(destinationUrl)
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player! = try AVAudioPlayer(contentsOf: destinationUrl, fileTypeHint: AVFileTypeMPEGLayer3)
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
}
我想知道下载文件并保存它,然后发挥它的最佳实践。
[错误代码听起来像是文件有问题。](https://www.osstatus.com/search/results?platform=all&framework=all&search=1685348671) –
哦,谢谢,我不知道关于这个网站!那么,我应该如何使用Alamofire下载文件并将其保存为mp3文件,或者如何从目标网址加载文件? – sphynx
你的代码在我看来没有任何问题。确保该文件是一个有效的MP3,而不是像404页面或什么的。 –